If you add a dictionary to a list in Python, it won’t create a copy of this dictionary, but rather add a reference to the dictionary.
Here’s how it works:
1 2 3 4 5 6 7 8 |
my_list = ['cat', 4, 'emu', 'dog', '.'] my_dict = {'animal': 'chicken'} my_list.append(my_dict) print(my_list) my_dict['animal'] = 'hen' print(my_list) |
This code will return the following result:
['cat', 4, 'emu', 'dog', '.', {'animal': 'chicken'}] ['cat', 4, 'emu', 'dog', '.', {'animal': 'hen'}]
Now, let’s think about what happened. The my_dict dictionary was added to the my_list list and printed. The result is what we expect. The second line may not be logical for some people. Why does changing my_dict also affect the list?
This happens because the list doesn’t have a copy of this object. It only contains a reference. That means, that if you change a directory object it affects the list.
If you want to add to a list a copy instead of a reference, you can do it by using the copy function.
1 2 3 4 5 6 7 8 |
my_list = ['cat', 4, 'emu', 'dog', '.'] my_dict = {'animal': 'chicken'} my_list.append(my_dict.copy()) print(my_list) my_dict['animal'] = 'hen' print(my_list) |
Now, if you try to run the code, changing the dictionary won’t affect the list, because they are two separate objects.
['cat', 4, 'emu', 'dog', '.', {'animal': 'chicken'}] ['cat', 4, 'emu', 'dog', '.', {'animal': 'chicken'}]