Home > Software design >  "IndexError: list index out of range" in very simple 3 lines of Python code
"IndexError: list index out of range" in very simple 3 lines of Python code

Time:01-15

I am a newbie to the programming and trying to understand how things work. I couldn't get my program to iterate through numpy.array normally, so I decided to try one level simple iteration through list. But still it wouldn't work! The code is as follows:

my_list = [1, 2, 3, 4, 5, 6, 7]
for i in my_list:
    print(my_list[i])

The output is:

So it doesn't take the my_list[0] index of some reason and comes out of range. Could you please help me to understand why?

CodePudding user response:

It's not clear what exactly you're trying to do. When you iterate over an iterable like a list with

for i in my_list:

each i is each member of the list, not the index of the member of the list. So, in your case, if you want to print each member of the list, use

for i in my_list:
    print(i)

Think about it: what if the 3rd member of the list was 9, for example? Your code would be trying to print my_list[9], which doesn't exist.

CodePudding user response:

As pointed out that's not how you should iterate over the elements of the list.

But if you persist, your loop be should over the range(my_list), at the moment you're indexing by the values of the list, and since the length is 7, the last valid index is 6, not 7.

CodePudding user response:

You get an IndexError, because you are looping through the values, which means, that your first value for i is 1 and the last one is 7. Because 7 is an invalid Index for this list you get an IndexError. A suitable code would be:

my_list = [1, 2, 3, 4, 5, 6, 7]
for i in my_list:
    print(i)
  •  Tags:  
  • Related