Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason behind this kind of behaviour when modifying elements while iterating through a python list [duplicate]

In the code below, modification of the first type changes the original list, while in the second list stays intact. Why is the behaviour the way it is?

temp = [{"a":"b"},{"c":"d"},{"e":"f"},{"a":"c"}]

for item in temp:
    if "a" in item:
        item["a"] = "x"
print(temp)
temp = [{"a":"b"},{"c":"d"},{"e":"f"},{"a":"c"}]

for item in temp:
    item  = {}
print(temp)

Output for the first one is [{'a': 'x'}, {'c': 'd'}, {'e': 'f'}, {'a': 'x'}]

and for the second one is [{'a': 'b'}, {'c': 'd'}, {'e': 'f'}, {'a': 'c'}]

Python version is 3.6.5

like image 272
Yash Gupta Avatar asked Nov 16 '25 08:11

Yash Gupta


1 Answers

for item in temp:
    item  = {}

In every iteration the list element item is discarded, and instead a new local variable (that just in chance happens to be called item as well) is created and assigned with an empty dict, which in turn is discarded as well. The original list is not affected at all.

This can be visualized with id, which returns the memory address of the object:

temp = [{}]
for item in temp:
    print(id(item))
    item = {}
    print(id(item))

Outputs

2704138237016
2704138237816

Notice how we are getting 2 different ids. 1 for the dict in the list, and another for the new dict created inside the loop.


Compared to

for item in temp:
    if "a" in item:
        item["a"] = "x"

here item is never reassigned with something else (no line says item = ...), so item always points to dict in the original list. You are assigning to the 'a' key of that original item dictionary.

like image 124
DeepSpace Avatar answered Nov 18 '25 23:11

DeepSpace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!