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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With