jolulop
jolulop

Reputation: 3

Problem understanding the Python interpreter internals

I have this very short piece of code but it's hard for me to understand how the Python interpreter works. I create a list and a dictionary with that list.

lista = [1,2,3]
dict = {1: lista}
print(lista)
print(dict)

This is the output, nothing strange here:

[1, 2, 3]
{1: [1, 2, 3]}

However, if I change the list so it now contains the dictionary...

lista = [1, dict]
print(lista)
print(dict)

I got this output:

[1, {1: [1, 2, 3]}]
{1: [1, 2, 3]}

The list is updated and I would expect that the dictionary would have a copy of the updated list, but this is not happening. I realize that I'm creating a loop and I assume that this loop is being handled in this way, so I would like to know it this is something defined by the Python language or by the Python interpreter implementation

Upvotes: 0

Views: 97

Answers (1)

chepner
chepner

Reputation: 530960

The dict still contains a reference to the original list. lista = [1, dict] does not modify that list; it only makes the name lista refer to a new list.

You may want to read https://nedbatchelder.com/text/names.html for a deeper exploration of how Python variables work.

Upvotes: 1

Related Questions