1
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.

asked Apr 17, 2019 at 23:52
8
  • 1
    for i in a: is iterating over the elements of a not the indexes. Thus, you are using the elements themselves as indexes into the list. Commented Apr 17, 2019 at 23:54
  • @JohanL How can I iterate over the indexes? Commented Apr 17, 2019 at 23:55
  • for i, e in enumerate(a): will give both the index and the value. Commented Apr 17, 2019 at 23:56
  • @davedwards As long as the element is not repeating. Commented Apr 17, 2019 at 23:57
  • 1
    Yes, that is true, i is the index and e is the element (or value). Commented Apr 18, 2019 at 0:00

3 Answers 3

4

You are referencing the value not the index. Try:

for i in range(len(a)):
 print(a[i])
JohanL
6,9211 gold badge16 silver badges32 bronze badges
answered Apr 17, 2019 at 23:55
Sign up to request clarification or add additional context in comments.

Comments

3

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)
answered Apr 17, 2019 at 23:58

Comments

1

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)
answered Apr 18, 2019 at 0:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.