Populating a list/array by index in Python?

后端 未结 7 1825
一整个雨季
一整个雨季 2021-01-31 17:02

Is this possible:

myList = []

myList[12] = \'a\'
myList[22] = \'b\'
myList[32] = \'c\'
myList[42] = \'d\'

When I try, I get:

#         


        
7条回答
  •  无人及你
    2021-01-31 17:25

    Not without populating the other locations in the list with something (like None or an empty string). Trying to insert an element into a list using the code you wrote would result in an IndexError.

    There's also mylist.insert, but this code:

    myList.insert(12,'a')
    

    would just insert 'a' at the first unoccupied location in the list (which would be 0 using your example).

    So, as I said, there has to be something in the list at indexes 0-11 before you can insert something at myList[12].

提交回复
热议问题