-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.

1
  • 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?) Commented Jul 30, 2022 at 3:23

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.