1

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?

0

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I understand now what you mean.
1

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.

1 Comment

Thank you! I understood my mistake.
0

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)

1 Comment

Thank you! I understand it now :)

Your Answer

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.