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 when index is past the end of the list; it simply appends obj to the list.
You could use a dictionary for this:
In [14]: d = {}
In [15]: d[42] = "foo"
In [16]: d[43] = "bar"
In [17]: d[44] = "baz"
In [18]: print(d[43])
bar
Alternatively, you could pre-initialize your list with a sufficiently large number of entries:
In [19]: l = [None] * 50
In [20]: l[42] = "foo"
In [21]: l[43] = "bar"
In [22]: l[44] = "bar"
In [23]: print(l[43])
bar
P.S. I recommend that you don't call your variable list as it shadows the list() builtin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With