Add Dictionary to a List in Python

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:

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.

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'}]