Search code examples
python-3.xlistindex-error

"IndexError: list index out of range" in very simple 3 lines of Python code


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?


Solution

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