Reputation: 99
I am really interested how Python memory allocation works.
I have written 2 pieces of code:
1.
list = []
a = [1,2,3]
list.append(a)
a = [3,2,1]
print(list)
print(a)
2.
def change(list):
list[1] = 50
list[2] = 70
list = []
a = [1,2,3]
list.append(a)
change(a)
print(list)
print(a)
When I compile the first code i get result [[1,2,3]] and [3,2,1].
However, when I compile the second code the result I get is [1,50,70].
In the first case I create an object "a" and an array "list". When I append my object "a" to the array, array points at it in fact. Then, when I am assigning "a" new array [3,2,1], the object [1,2,3] is saved in the array and "a" points at new array [3,2,1].
In the second case I also create an object "a" and an array "list". I append "a" to array and there's also a pointer, that points at "a". Then I'm calling a method on an array "a". After calling the function and changing the value of the elements, array "list" still points at object "a" without creating a new instance.
Can somebody explain me the way it really works?
Upvotes: 2
Views: 115
Reputation: 3520
Every variable you create in Python is a reference to an object. Lists are objects which contain multiple references to different objects.
Almost all operations in python modify these references, not the objects. So when you do list[1] = 50
you are modifying the second reference that the list item contains.
I have found that a useful tool for visualising this is Python Tutor
So for your first example
list = [] # you create a reference from `list` to the the new list object you have created
a = [1,2,3] # you create a reference from `a` to the new list you have created which itself contains 3 references to three objects, `1`, `2` and `3`.
list.append(a) # this adds another reference to `list` to the object referenced by `a` which is the object `[1, 2, 3]`
a = [3,2,1] # create a reference from `a` to the new list you have created which itself contains 3 references to three objects, `3`, `2` and `1`.
print(list) # print the object referenced by `list`
print(a) # print the object referenced by `a`
For your second example
def change(list): # create a reference from `change` to a function object
list[1] = 50 #change the second reference in the object referenced by `list` to `50`
list[2] = 70 #change the third reference in the object referenced by `list` to `70`
list = [] # create a reference from `list` to a new list object
a = [1,2,3] # create a reference from `a` to a new list object which itself contains three references to three objects, `1`, `2` and `3`.
list.append(a) # add a reference to list to the object pointed to by `a`
change(a) # call the function referenced by change
print(list) # print the object referenced by `list`
print(a) # print the object referenced by `a`
Upvotes: 3