-1

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Marsl
  • 285
  • 1
  • 10
  • To the extent that the question isn't answered by the linked duplicate, it lacks focus or is unclear (what exactly are we trying to "get around"? Was `el = foo()` intended to modify `a`? If so, was that the intended primary question?) – Karl Knechtel Jul 30 '22 at 03:23

1 Answers1

1

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]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343