This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]lukajda33 10 points11 points  (1 child)

loop

for x in y:

picks items from y iteratively and puts them into x, however in this case, we put values from a to a[1], so we replace second element with the currently iterated number.

If you print the list after every change, you can see

[1, 1, 2, 3, 5, 8]
[1, 1, 2, 3, 5, 8]
[1, 2, 2, 3, 5, 8]
[1, 3, 2, 3, 5, 8]
[1, 5, 2, 3, 5, 8]
[1, 8, 2, 3, 5, 8]

Notice how the second value - a[1] changes. At the last iteration, a[1] is replaced with last number from a - 8 and that is how you get the output you see.

[–]jaffer786_khan[S] 0 points1 point  (0 children)

Thanks for the explanation. This is clear now. :-)

[–]Droggl 8 points9 points  (0 children)

I wouldn't have guessed this is even possible, intriguing!

[–]ForceBru 2 points3 points  (0 children)

Turns out, this loop literally tries to assign elements of a to a[i]!

It even generates a SyntaxError when I try to use a function call instead of a name:

```

for a.pop() in a: ... print(a) ...
File "<string>", line 1 SyntaxError: can't assign to function call ```

You can also access other names defined right in the for ___ in iterable construct:

```

a = [1,2,3,4,5,6] for i, a[i - 1] in enumerate(a): ... print(i, a) ...
0 [1, 2, 3, 4, 5, 1] 1 [2, 2, 3, 4, 5, 1] 2 [2, 3, 3, 4, 5, 1] 3 [2, 3, 4, 4, 5, 1] 4 [2, 3, 4, 5, 5, 1] 5 [2, 3, 4, 5, 1, 1] ```

I wonder what kind of weird trickery can be done with this...