I have an empty python list. and I have for loop that insert elements with index but at random (means indices are chosen randomly to insert the item). I tried a simple example, with randomly select indices, but it works in some indices but others won't work. Below is a simple example of what I wanna do:
a=[]
#a=[]
a.insert(2, '2')
a.insert(5, '5')
a.insert(0, '0')
a.insert(3, '3')
a.insert(1, '1')
a.insert(4, '4')
The output of this is a = ['0','1','2','5','4','3'] it's correct in the first three (0,1,2) but wrong in the last three ('5','4','3')
How to control insert to an empty list with random indices.
5, it has no meaning because the element will be the first and only element of the list anyway... You might want to initialize the list with some default value, or make sure you padd it with a default value everytime you insert in an index greater than the list's size...a.insert(random.randint(0, len(a)), v)where v is the value to insert. Note with empty list, len(a)=0 so will insert at position 0 as expected. This is from How to insert elements into the list at arbitrary positions?