Python列表插入索引

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')

其输出为a = ['0','1','2','5','4','3'] 前三个(0,1,2)是正确的,但后三个('5','4','3')是错误的

如何控制插入到具有随机索引的空列表。

评论
Rabbit_19C
Rabbit_19C

list.insert(e, i) will insert the element e before the index i, so e.g. for an empty list it will insert it as the first element (obviously).

Keep in mind that lists are not fixed sized arrays.

点赞
评论