This time, it is an experiment to take a deeper look at what a variable points to. The version of python is 3.4.3.
Even if you assign the contents of a variable to another variable, it points to the same object. Check this by comparing the object ids.
mylist = [[0, "mike"], [1, "jane"]]
person1 = mylist[0]
print("mylist = %s" % mylist)
print("person1 = %s" % person1)
# =>
# mylist = [[0, 'mike'], [1, 'jane']]
# person1 = [0, 'mike']
#Make sure the two variables point to the same object
print("mylist[0] id = %s" % id(mylist[0]))
print("person1 id = %s" % id(person1))
print(id(mylist[0]) == id(person1))
# => True
#Save the current object id for later confirmation
person1_id = id(person1)
Try changing the elements of the array through another variable. Only when a subscript is specified
#person is mylist[0]Make sure it is an alias for
person1[0] = 100
print("mylist = %s" % mylist)
print("person1 = %s" % person1)
# =>
# mylist = [[100, 'mike'], [1, 'jane']]
# person1 = [100, 'mike']
The element has been changed successfully. However, if you don't use subscripts, you can't change the element and a new object is assigned.
#through pesron1 mylist[1]Attempt to change the array of
person1 = [5, "michel"]
print("mylist = %s" % mylist)
print("person1 = %s" % person1)
# =>
# mylist = [[100, 'mike'], [1, 'jane']]
# person1 = [5, 'michel']
person1 = 5
print("mylist = %s" % mylist)
print("person1 = %s" % person1)
# =>
# mylist = [[100, 'mike'], [1, 'jane']]
# person1 = 5
If you compare it with the object id when the elements of the previous array were included, you can see that the object has certainly changed.
#Compare with id before changing object
print(person1_id == id(person1))
# => False
Let's illustrate the above phenomenon. First is the case of using subscripts. Note that when we use subscripts, we are not pointing to an array (list in this case), but to its elements. Since we just changed the reference (arrow) of the element of the array, the variable that was referencing the array remains the reference of the array.
Next is the case without subscripts. In the previous experiment, in this case, changing the value from another variable did not affect the original variable. This is because I changed the reference to the array to a reference to a new object.
Recommended Posts