I'm trying to enumerate through list d of the dict a and transfer them to list c.
Not working:
a = {"c": [], "d": [1, 2, 3]}
b = a
for index, value in enumerate(a["d"]):
print(value)
b["c"].append(b["d"].pop(b["d"].index(value)))
print(b)
Output:
1
{'c': [1], 'd': [2, 3]}
3
{'c': [1, 3], 'd': [2]}
Working:
a = {"c": [], "d": [1, 2, 3]}
b = {"c": [], "d": [1, 2, 3]} # <- Changed to the exact same dict
for index, value in enumerate(a["d"]):
print(value)
b["c"].append(b["d"].pop(b["d"].index(value)))
print(b)
Output:
1
{'c': [1], 'd': [2, 3]}
2
{'c': [1, 2], 'd': [3]}
3
{'c': [1, 2, 3], 'd': []}
So why is only the second one working?
CodePudding user response:
Your first code has a single dictionary, and its address is saved in both a and b variables. So a["c"] is the same list as b["c"], and a["d"] is the same list as b["d"].
Then you start iterating on the list a["d"]. In the first iteration, the index is 0, and you pop the value 1 as b["d"][0] which is the same as a["d"][0]. Notice that now the value 2 is located in the index 0, and you will never iterate on it. In the second iteration, the index is 1, and you pop the value 3 which is now located in the index 1.
Your second code has two separate independent dictionaries. Their addresses are stored in variables a and b. Also, you have four independent lists (a["c"], a["d"], b["c"], and b["d"]). You are iterating on a["d"], but you pop items from b["d"] which is another list. So, when you pop an element from b["d"], that element does still exist in b["a"], and doesn't make any change in your iteration.
In your first code, the loop iterates 2 times to reach the end of the list (because you are deleting elements from the list), but in the second code, the loop iterates 3 times.
CodePudding user response:
a = {"c": [], "d": [1, 2, 3]}
b = {"c": [], "d": [1, 2, 3]} # <- Changed to the exact same dict
a['c'].append(a['d'])
a['d']=[]
print(a)
