a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in a:
print(a[i])
IndexError: list index out of range
I don't undertand why I get this error.
If you want the index of an element, it is possible to enumerate the data in the array, using
for i, e in enumerate(a):
print(a[i]) # assuming this is just a placeholder for a more complex instruction
gives what you want, where i is the index and eis the (value of) the element in the list. But often you do not need the index since you want to use the value of the element directly. In those cases it is better to do just
for e in a:
print(e)
for i in a:is iterating over the elements ofanot the indexes. Thus, you are using the elements themselves as indexes into the list.for i, e in enumerate(a):will give both the index and the value.iis the index andeis the element (or value).