In 100 days of code with python (anjella yu), teacher appends objects with same name to a list and i can't figure out how same name objects can be created. Can somebody explain me?
my_list=[]
For _ in range(10):
new_object=turtle()
my_list.apend(new_object)
As you can see 10 objects with same name are created and appended to my_list
CodePudding user response:
A list is just a collection of objects. The only way you can refer to each is by its numeric index (eg my_list[0], my_list[1], etc.). Therefore, they have no "names". So, assuming that turtle() returns an object, the new object just gets added to the next position in my_list.
This is different than sets and dictionaries. In a set, an object can exist only once. So, if you send the same object twice, it will only end up in the set once.
Similarly for dictionaries. The "key" in a dictionary is a sort of name for the object it represents. If you provide two objects with the same key, the second one you provide will overwrite the first.
CodePudding user response:
new_object
is just one name that refers to an instance of turtle
. my_list.append(new_object)
adds another reference to the same object to the list; that reference does not change when the name new_object
is made to refer to a different object.
Put another way, you are not adding the name new_object
to the list, but a reference to the object the name refers to. (You could also have written my_list.append(turtle())
without defining the variable new_object
at all; the result would be the same.)
Once the loop completes, you have a list containing references to 10 different objects, and the name new_object
still refers to the last object created.
CodePudding user response:
I have slightly modified your code here, but the essense is the same.
>>> my_list = []
>>> for _ in range(10):
... new_object = dict()
... my_list.append(new_object)
...
>>> my_list
[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
>>> my_list[0]
{}
>>> my_list[1]
{}
>>> id(my_list[0])
140200988731072
>>> id(my_list[1])
140200988731136
>>> id(my_list[3])
140200988731264
>>> id(my_list[4])
140200988731328
>>> id(my_list[2])
140200988731200
>>>
As you can see that my_list's first, second or third object are visible the same and none of them have any content but they are different.
In Python id
(inbuilt function) is used to identify the unique hash code given to each object living in the python memory. So as I check them, each object has a unique id.
As you may now understand, every object is Python is identified by its unique id not by its visible name. Also Python list uses pointers(internally) to hold on to its objects. So each unique/new object has a new memory location or new pointer location.