limitless limitless - 2 years ago 71
Python Question

Weird for loop statement

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

Answer Source

The for loop uses a[-1] as a target variable. The for loop assigns each value in the list to that one variable. 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.

The for loop grammar 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download