Fully understand for loop python

Question:

I start out with a small code example right away:

def foo():
    return 0

a = [1, 2, 3]

for el in a:
    el = foo()

print(a) # [1, 2, 3]

I would like to know what el is in this case. As a remains the same, I intuite that el is a reference to an int. But after reassigning it, el points to a new int object that has nothing to do with the list a anymore.

Please tell me, if I understand it correctly. Furthermore, how do you get around this pythonic-ly? is enumerate() the right call as

for i, el in enumerate(a):
    a[i] = foo()

works fine.

Asked By: Marsl

||

Answers:

Yes, you understood this correctly. for sets the target variable el to point to each of the elements in a. el = foo() indeed then updates that name to point to a different, unrelated integer.

Using enumerate() is a good way to replace the references in a instead.

In this context, you may find the Facts and myths about Python names and values article by Ned Batchelder helpful.

Another way would be to create a new list object altogether and re-bind a to point to that list. You could build such a list with a list comprehension:

a = [foo() for el in a]
Answered By: Martijn Pieters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.