Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.x for loops and list indexing

I'm having trouble understanding, this simple question using for loop in Python, which I found in an online quiz. Can you please help me understand, why we are getting the below output?

some_list = [1,2,3,4,5]

for some_list[1] in some_list:
    print(some_list)
    print(some_list[1])

output:

[1, 1, 3, 4, 5]
1
[1, 1, 3, 4, 5]
1
[1, 3, 3, 4, 5]
3
[1, 4, 3, 4, 5]
4
[1, 5, 3, 4, 5]
5

I thought, it would print the 2nd element of the list and the whole list 5 times.

like image 530
chqdrian Avatar asked Aug 31 '26 11:08

chqdrian


1 Answers

The expression for x in some_list: loops through a list and temporarily stores each value of the list in x.

The expression for some_list[1] in some_list: loops through a list and temporarily stores each value of the list in some_list[1]. (Each iteration of the loop, the next value of the list is over-writing some_list[1].)

I thought, it would print the 2nd element of the list and the whole list 5 times.

That is what's happening, it's just that the list is changing (particularly the 2nd element).

like image 136
Bill the Lizard Avatar answered Sep 02 '26 14:09

Bill the Lizard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!