Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird for loop statement [duplicate]

I saw this for loop and I didn't quite understood why the last print is 2. Why it isn't 3 ?

a = [0, 1, 2, 3]

for a[-1] in a:
    print(a[-1])

out:

0
1
2
2
like image 583
limitless Avatar asked Jan 27 '16 19:01

limitless


1 Answers

The for loop uses a[-1] as a target variable, assigning each value from the input iterable:

for <target> in <iterable>

The for loop assigns each value in the a list to that one target, a[-1]. That happens to also be the last element in that same list.

So the list changes with each step through the loop:

>>> a = [0, 1, 2, 3]
>>> for a[-1] in a:
...     print a
...
[0, 1, 2, 0]  # assigned a[0] == 0 to a[-1] (or a[3])
[0, 1, 2, 1]  # assigned a[1] == 1 to a[-1]
[0, 1, 2, 2]  # assigned a[2] == 2 to a[-1]
[0, 1, 2, 2]  # assigned a[3] == 2 (since the previous iteration) to a[-1]

The one-but-last iteration assigns puts a[2] into a[3] (or a[-2] into a[-1]), and that is why, when the last iteration takes place, you see 2 again.

See the for loop grammar; it takes a generic target_list for the assignment target, just like an assigment statement. You are not limited to just simple names in assignments, and neither are you in a for loop.

like image 71
Martijn Pieters Avatar answered Oct 06 '22 08:10

Martijn Pieters