Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python self referencing for loops

a = [0, 1, 2, 3]
for a[-1] in a:
    print(a[-1])

The output is 0 1 2 2

Why does a[-1] change with each iteration?

like image 246
weasel Avatar asked Oct 31 '25 21:10

weasel


2 Answers

Your code is equivalent to:

a[-1] = a[0]
print(a[-1])

a[-1] = a[1]
print(a[-1])

a[-1] = a[2]
print(a[-1])

a[-1] = a[3]
print(a[-1])

Each time through the loop it assigns the value of the current list element to a[-1] and then prints it.

like image 185
Barmar Avatar answered Nov 02 '25 13:11

Barmar


You are the changing a[-1] value while iterating. The iterating variable is a reference to objects in the iterable.

lst = [[1, 2], [3, 4]]

#    ---> Iterating variable
#    |
for val in lst:
    val.append(55)
print(lst)
# [[1, 2, 55], [3, 4, 55]]

Because a is a reference to objects you're iterating over.

In your case, your iterating variable is a[-1] itself. So, you keep on changing a[-1]. You can debug by adding print(...) statements here.

a = [0, 1, 2, 3]
for a[-1] in a:
    print(a)

[0, 1, 2, 0] # a[-1] == a[0]
[0, 1, 2, 1] # a[-1] == a[1]
[0, 1, 2, 2] # a[-1] == a[2]
[0, 1, 2, 2] # a[-1] == a[3]
like image 21
Ch3steR Avatar answered Nov 02 '25 12:11

Ch3steR



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!