Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access a list by its key in Python?

Tags:

python

list

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 ?

like image 208
Benjamin Crouzier Avatar asked Feb 23 '26 23:02

Benjamin Crouzier


1 Answers

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.

like image 129
NPE Avatar answered Feb 25 '26 11:02

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!