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
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With