Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing by assignment: Python

I wanted to make sense of the following code variations:

a = [1, 2, 3]
b = a
b.append(4)
b = ['a', 'b']
print(a, b)

What I understood was that variable a refers to an object that contains the list [1,2,3] in some place in memory, and b now is referring to the same object that a is referring to, and via that link we're technically appending in a not b.

Output: [1, 2, 3, 4] ['a', 'b']

I updated the code a bit:

a = [1, 2, 3]
b = ['a', 'b']
b = a
b.append(4)
print(a, b)

My understanding: b is now referring to two objects, the first list ['a','b'] and the second list (that a is initially referring to) [1,2,3] via the third line b = a.

Output: [1, 2, 3, 4] [1, 2, 3, 4]

Last Code variation:

a = [1, 2, 3]
b = ['a', 'b']
b = a
b.append(4)
a.append(10)
print(a, b)

based on my understanding so far, I though that the link on line 3 b = a was giving only b the ability to reference multiple objects (it's own and a's) and a should've only be referencing one object [1,2,3], so the expected output should be: [1,2,3,4,10] [1,2,3,4]

Actual Output: [1, 2, 3, 4, 10] [1, 2, 3, 4, 10]

So is this assignment on line 3 b = a is like a bi-directional link? where also a reference is created by a to b's object?

like image 647
Ahmed Alhallag Avatar asked Jun 08 '26 07:06

Ahmed Alhallag


1 Answers

My understanding: b is now referring to two objects, . . .

That is not correct. A name cannot be associated with multiple objects within a given scope at the same time.

b = a associates b with the object that a is associated with. After that line has executed, nothing will be referencing ['a', 'b'], and that list should be eligible for garbage collection because it can no longer be used.

like image 182
Carcigenicate Avatar answered Jun 10 '26 13:06

Carcigenicate



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!