Is Python call-by-value or call-by-reference? Neither.

There is one tricky but very popular problem I often encounter. How do you deal with value assignment in Python, for variable, list and tuple?

In fact, this question has been answered by many people and I want to brief my thinking and list the reference.

In Python (and other languages), a variable (and object fields, and entries in collections, etc.) is a just a name. Values are somewhere else (e.g. sprinkled all over the heap), and a variable refers (not in the sense of C++ references, more like a pointer minus the pointer arithmetic) to a value. Multiple names can refer to the same value (which is generally a good thing). Python (and other languages) calls whatever is needed to refer to a value a reference, despite being pretty unrelated to things like C++ references and pass-by-reference. Assigning to a variable (or object field, or …) simply makes it refer to another value. The whole model of storage locations does not apply to Python, the programmer never handles storage locations for values. All he stores and shuffles around are Python references, and those are not values in Python, so they cannot be target of other Python references.

All of this is independent of mutability of the value – it’s the same for ints and lists, for instance. You cannot take a variable that refers to either, and overwrite the object it points to. You can only tell the object to modify parts of itself – say, change some reference it contains.

One example:

### Immutable
a = 1
b = a # At this moment, a -> 1 <- b
b = 2 # At this moment, a -> 1, 2 <- b
# What is a then? a should be 1.

### Mutable, in fact this is nothing related to immutable and mutable
# Case 1
a = [1,2,3]
b = a # At this moment, a -> [1,2,3] <- b
a = [0,0] # At this moment, a -> [0,0], [1,2,3] <- b
# Now b is [1,2,3]

# Case 2
a = [1,2,3]
b = a # At this moment, a -> [1,2,3] <- b
a[:] = [0,0] # At this moment, we change the original list of a, a -> [0,0] <- b
# Now b is [0,0]

Ref:

https://stackoverflow.com/questions/11222440/python-variable-reference-assignment

https://jeffknupp.com/blog/2012/11/13/is-python-callbyvalue-or-callbyreference-neither/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: