Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does variable copying in Python exactly work?

Why is it that:

 >>> a = 1
 >>> b = a
 >>> a = 2
 >>> print(a)
 2
 >>> print(b)
 1

...but:

 >>> a = [3, 2, 1]
 >>> b = a
 >>> a.sort()
 >>> print(b)
 [1, 2, 3]

I mean, why are variables really copied and iterators just referenced?

like image 968
Laurent Avatar asked Oct 19 '25 13:10

Laurent


2 Answers

Variables are not "really copied". Variables are names for objects, and the assignment operator binds a name to the object on the right hand side of the operator. More verbosely:

>>> a = 1 means "make a a name referring to the object 1".

>>> b = a means "make b a name referring to the object currently referred to by a. Which is 1.

>>> a = 2 means "make a a name referring to the object 2". This has no effect on which object anything else that happened to refer to 1 now refers to, such as b.

In your second example, both a and b are names referring to the same list object. a.sort() mutates that object in place, and because both variables refer to the same object the effects of the mutation are visible under both names.

like image 190
Peter DeGlopper Avatar answered Oct 21 '25 01:10

Peter DeGlopper


Think of the assigned variables as pointers to the memory location where the values are held. You can actually get the memory location using id.

a = 1
b = a

>>> id(a)
4298171608

>>> id(b)
4298171608  # points to the same memory location

a = 2
>>> id(a)
4298171584  # memory location has changed

Doing the same with your list example, you can see that both are in fact operating on the same object, but with different variables both pointing to the same memory location.

a = [3, 2, 1]
b = a
a.sort()

>>> id(a)
4774033312

>>> id(b)
4774033312  # Same object
like image 20
Alexander Avatar answered Oct 21 '25 02:10

Alexander