I am creating a list, and then accessing an element like this:
list = []
list.insert(42, "foo")
list.insert(43, "bar")
list.insert(44, "baz")
print(list[43])
And I have the folowing error:
print(list[43]) IndexError: list index out of range
What is wrong ? Do I have to use a dictionary to do this ?
There are no “keys” in a list, there are just indices.
The reason your code doesn’t work the way you expect is that
list.insert(index, obj)does not pad the list with “blank” entries whenindexis past the end of the list; it simply appendsobjto the list.You could use a dictionary for this:
Alternatively, you could pre-initialize your list with a sufficiently large number of entries:
P.S. I recommend that you don’t call your variable
listas it shadows thelist()builtin.