Jump to

v12-l1-createObj

How many different objects are created with in the following Python code ?

a = "hello"
b = a

myList = [a, b, a+b]
c = myList[-1]

myTuple = (myList, myList[1])

???

First object is created with a = "hello".

Then when doing b=a, we simply assign a new name to the variable stored by a, so it does not create a new objects, both are the same. You can test it by running right after

a = "hello"
b = a
id(a) == id(b) # => True

Then when creating myList, we create a list object, containing two different name for an object that already exists (a and b) and a newly created object a+b. So here we are at 3 objects created.

No object is created when defining c, since it is just defining a new name to the last element of myList (a+b) that already exists.

Finally, the fourth object is created when instantiating the tuple myTuple, which stores a reference to myList in first position (no copy is done), and another one to the second element of myList in second position (i.e b).

🔔 Something you should always remember in Python, is that it never does copy assignment implicitly, as it could be done in C++ for instance.