Chipmunkafy
Chipmunkafy

Reputation: 586

Python: For loop list gives IndexError

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.

Upvotes: 1

Views: 58

Answers (3)

Ethan
Ethan

Reputation: 1373

You are referencing the value not the index. Try:

for i in range(len(a)):
    print(a[i])

Upvotes: 4

JohanL
JohanL

Reputation: 6891

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)

Upvotes: 1

blhsing
blhsing

Reputation: 106543

You don't actually need an index in the example you give, since you are only printing the values of the items in the list, in which case printing the items directly would suffice:

for i in a:
    print(i)

Upvotes: 3

Related Questions