Kris R.
Kris R.

Reputation: 13

Python 3.4 - Range object index out of range

I apologize if this has been asked before, but I want to print all of the elements of a list called "my_list."

This code works:

my_list = range(75)

for i in my_list:
    print (my_list[i])

But this code...

my_list = range(1, 75)

for i in my_list:
    print (my_list[i])

...generates the following error: IndexError: range object index out of range

How can this be fixed?

Upvotes: 0

Views: 5933

Answers (4)

Farhan Ansari
Farhan Ansari

Reputation: 299

It's simple you have to code as below.

my_list = range(0, 76)

for i in my_list:
    print (my_list[i])

put this code this will clear your IndexError: list index out of range. [Solved]

Upvotes: 0

Adam Smith
Adam Smith

Reputation: 54163

range(1, 75) represents the numbers 1..74. It has indices 0..73.

my_list[74] will IndexError since the largest index is 73.


As other answers have mentioned, it seems you've mistaken indices for values. for foo in bar in Python gives you all the VALUES in bar, not the indices.

enumerate is a common tool to get both index and value from an iterable. It's a bit silly on a range object, but you could do it:

my_list = range(1, 75)

for i, val in enumerate(my_list):
    print(my_list[i])  # my_list[i] == val

enumerate(bar) is essentially just zip(range(len(bar)), bar).

Upvotes: 4

John Sensebe
John Sensebe

Reputation: 1396

You're iterating through every i in my_list. You want to be printing i:

my_list = range(1, 75)

for i in my_list:
    print i

Upvotes: 0

Prune
Prune

Reputation: 77837

You can just iterate through the list; you're confusing indices with elements. You one one of the following:

for i in my_list:
    print (i)

-- OR --

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

To illustrate a more severe version of what you did, try this:

my_list = range(5, 15)
print my_list

for i in range(5, 15):
    print (i, my_list[i])

Output:

[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
5 10
6 11
7 12
8 13
9 14
10
IndexError: list index out of range

Upvotes: 2

Related Questions