0
x=[1,2,3,4,5]
for x[2] in x:
   print(x[2])
print(x)

Output:

1
2
2
4
5
[1, 2, 5, 4, 5]

can somebody throw some light on what is happening here and how is the list changed? ​

  • 1
    It's reassigning `x[2]` on each loop, from whatever is in `x[2]` at the time. Work it out a loop at a time. – ShadowRanger Jul 15 '20 at 20:48
  • You're assigning `x[2]` to each element of `x` in turn. – khelwood Jul 15 '20 at 20:48
  • It might help to `print(x)` in the for loop to see what is happening – ScootCork Jul 15 '20 at 20:54
  • Very important to understand, iterator is **not** the correct terminology in Python, if you mean the `x[2]` in the `for x[2] in x`. An *iterator* is an object that defins an `__iter__` method which must return `self` and `__next__` method. Iterators are returned from iterables when you call `iter` on them. Anyway, it is very simple, in a for-loop, `for in iterable:` will essentially get assigned **whatver the iterator created from the iterable returns from `next`. So, you can think of it like at the top of the for-loop, it is doing `x[2] = next(iterator)`. – juanpa.arrivillaga Jul 15 '20 at 20:54
  • @mkrieger1 there definitely is. Basically, in the for-loop syntax, any valid assignment target can go there, that is why you can use iterable unpacking assignment, etc. Perhaps there is no good reason to *allow* the above, but I think it is allowed merely because it wasn't thought it was important enough to disallow... – juanpa.arrivillaga Jul 15 '20 at 20:58
  • [Here is the relevant docs](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement). Note, for a for-loop statement, you are referring to the "target list". From the docs: "The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order returned by the iterator. Each item in turn is assigned to the target list using the standard rules for assignments (see Assignment statements), and then the suite is executed." – juanpa.arrivillaga Jul 15 '20 at 21:03

1 Answers1

3

You are implicitly telling python to do this:

for x_element in x:
    x[2] = x_element
    print(x[2])
print(x)

because in the for loop you are assigning to x[2] the iterated element.
Hence, when you get to index 2, you just assigned to x[2] the previous value (x[1], which is 2). And when you end the loop X[2] was assigned x[4], that is 5, in the last iteration.

But please, do not use this code!

Red
  • 26,798
  • 7
  • 36
  • 58
eguaio
  • 3,754
  • 1
  • 24
  • 38