I encountered behavior in Python that I didn't expect when appending a dictionary to a list. Specifically, I tried
list_val=[]
local_dict={}
for val in ['a', 'b', 'c']:
local_dict['first']=val
list_val.append(local_dict)
print(list_val)
which produces
[{'first': 'a'}]
[{'first': 'b'}, {'first': 'b'}]
[{'first': 'c'}, {'first': 'c'}, {'first': 'c'}]
Using the page pythontutor.com I'm able to watch the steps execute and I see that each list element points to the same dictionary that is being altered.
The fix is to declare the dictionary inside the loop,
list_val=[]
for val in ['a', 'b', 'c']:
local_dict={}
local_dict['first']=val
list_val.append(local_dict)
print(list_val)
which produces
[{'first': 'a'}]
[{'first': 'a'}, {'first': 'b'}]
[{'first': 'a'}, {'first': 'b'}, {'first': 'c'}]
The reason the behavior is unexpected is because I'm used to appending values to list like this:
list_val=[]
for val in ['a', 'b', 'c']:
list_val.append(val)
print(list_val)
which produces
['a']
['a', 'b']
['a', 'b', 'c']
Where should I expect to see pointer-like behavior?
I saw this question but my observation isn't related to functions.