Values and references

suggest change

In Python every value is an object, and a variable is just a name that refers to an object. Assignment binds a name to an object. It never copies the object. Once that is clear, a lot of puzzling behavior starts to make sense: why changing one list changes "another" one, why a function can change your list but not your integer, and why [[0] * 3] * 3 gives a strange grid.

This article covers:

All examples were run with Python 3.13.

Names refer to objects

When you write b = a, Python does not create a new list. Both names now refer to the same object:

a = [1, 2, 3]
b = a

print(a is b)
print(id(a) == id(b))

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

id(obj) returns a number that is unique to the object for as long as it is alive (in CPython it is the memory address). a is b is the same test as id(a) == id(b): it asks whether two names refer to the same object.

Because a and b are two names for one list, a change made through b is visible through a. This is called aliasing.

Rebinding vs. mutating

There are two very different things you can do with a name:

Rebinding a name never affects other names:

a = [1, 2, 3]
b = a

b = [10, 20]      # rebinding: b now refers to a different list
print(a)
print(b)
print(a is b)
[1, 2, 3]
[10, 20]
False

Mutation affects every name that refers to the object. Only mutable objects (lists, dicts, sets, most class instances) can be mutated. Immutable objects (int, float, str, bytes, tuple, frozenset, None) can't be changed at all. Every "change" produces a new object. See Mutable vs Immutable for a list of types.

Augmented assignment

+= is where the two ideas meet. For immutable types x += 1 creates a new object and rebinds x. For a list, += mutates the list in place (it calls list.__iadd__, which works like extend):

x = 10
y = x
y += 1
print(x, y)

nums = [1, 2]
alias = nums
alias += [3]          # list += mutates in place
print(nums, alias)

alias = alias + [4]   # + creates a new list, then rebinds alias
print(nums, alias)
10 11
[1, 2, 3] [1, 2, 3]
[1, 2, 3] [1, 2, 3, 4]

You can confirm this with id():

s = "abc"
before = id(s)
s += "d"
print("str same object:", id(s) == before)

lst = [1]
before = id(lst)
lst += [2]
print("list same object:", id(lst) == before)
str same object: False
list same object: True

Equality vs. identity

== compares values (it calls __eq__). is compares identity. Two separate lists with the same contents are equal but not identical:

a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)   # same value
print(a is b)   # different objects
print(a is c)   # same object

result = None
print(result is None)
True
False
True
True

Use is only for singletons: None, True, False, Ellipsis, or sentinel objects you created yourself. Always write x is None, not x == None. A class can define __eq__ to return anything, so == can lie, while is can't:

class AlwaysEqual:
    def __eq__(self, other):
        return True

x = AlwaysEqual()
print(x == None)
print(x is None)
True
False

Don't use is to compare numbers or strings

CPython caches small integers (-5 to 256) and interns some strings, so is sometimes returns True for equal values. That is an implementation detail and you should not rely on it:

a = 256
b = 256
print(a is b)

a = int("1000")
b = int("1000")
print(a == b, a is b)

s1 = "".join(["he", "llo"])
s2 = "hello"
print(s1 == s2, s1 is s2)
True
True False
True False

Python 3.8+ also warns about it: writing x is 1000 with a literal gives SyntaxWarning: "is" with 'int' literal. Did you mean "=="?. More on this in Integer and String identity and Comparison by is vs ==.

Passing arguments to functions

Python passes arguments neither "by value" nor "by reference" in the C++ sense. When you call a function, the parameter name is bound to the same object that the caller passed. This is often called pass by assignment or call by sharing: it works exactly like param = argument.

def show(obj):
    print(id(obj))

value = [1, 2]
print(id(value))
show(value)
1348945338496
1348945338496

So the same rules apply as for plain assignment:

def add_item(items, item):
    items.append(item)       # mutates the caller's list

def replace_items(items):
    items = ["new"]          # rebinds the local name only
    return items

data = ["a"]
add_item(data, "b")
print(data)

result = replace_items(data)
print(data)
print(result)
['a', 'b']
['a', 'b']
['new']

Since immutable objects can't be mutated, a function can never change the caller's int, str or tuple. If a function needs to "change" one, it returns the new value:

def increment(n):
    n += 1
    return n

count = 5
new_count = increment(count)
print(count, new_count)
5 6

Mutate or return, but say which

Code is easier to follow when a function either returns a new object or modifies its argument in place and returns None. The standard library follows this rule: sorted(lst) returns a new list, while lst.sort() sorts in place and returns None.

def normalize(scores):
    """Return a new list; leave the caller's list alone."""
    top = max(scores)
    return [s / top for s in scores]

def normalize_in_place(scores):
    """Modify the list and return None, like list.sort()."""
    top = max(scores)
    for i, s in enumerate(scores):
        scores[i] = s / top

raw = [2, 5, 10]
print(normalize(raw), raw)

normalize_in_place(raw)
print(raw)
[0.2, 0.5, 1.0] [2, 5, 10]
[0.2, 0.5, 1.0]

See also Argument passing and mutability.

Containers store references

A list, dict or set doesn't hold copies of its items, only references to them. Most aliasing bugs come from forgetting this.

Loop variables

The loop variable is bound to each item in turn. Mutating it changes the container's item. Rebinding it does nothing to the container:

matrix = [[1, 2], [3, 4]]
for row in matrix:
    row.append(0)        # row refers to the inner list: this changes matrix
print(matrix)

numbers = [1, 2, 3]
for n in numbers:
    n *= 10              # n is rebound to a new int; numbers is unchanged
print(numbers)

numbers = [n * 10 for n in numbers]
print(numbers)
[[1, 2, 0], [3, 4, 0]]
[1, 2, 3]
[10, 20, 30]

Appending the same object repeatedly

Here the same dict is appended three times, so all three entries show the last value:

rows = []
row = {}
for i in range(3):
    row["n"] = i
    rows.append(row)
print(rows)

rows = []
for i in range(3):
    row = {"n": i}          # a new dict on each iteration
    rows.append(row)
print(rows)
[{'n': 2}, {'n': 2}, {'n': 2}]
[{'n': 0}, {'n': 1}, {'n': 2}]

List multiplication

[x] * 3 makes a list with three references to the same x. That's fine when x is an immutable number, but not when it is a list:

grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)
print(grid[0] is grid[1])

grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
print(grid)
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
True
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]

The comprehension evaluates [0] * 3 once per row, so each row is a separate list. See List multiplication and common references.

dict.fromkeys with a mutable value

dict.fromkeys(keys, value) uses the same value object for every key:

groups = dict.fromkeys(["a", "b"], [])
groups["a"].append(1)
print(groups)

groups = {key: [] for key in ["a", "b"]}
groups["a"].append(1)
print(groups)
{'a': [1], 'b': [1]}
{'a': [1], 'b': []}

collections.defaultdict(list) is another good option.

Mutable default arguments

Default values are evaluated once, when the def statement runs, not on every call. A mutable default is shared by every call that doesn't pass the argument:

def append_to(item, target=[]):
    target.append(item)
    return target

print(append_to(1))
print(append_to(2))

def append_to_fixed(item, target=None):
    if target is None:
        target = []
    target.append(item)
    return target

print(append_to_fixed(1))
print(append_to_fixed(2))
[1]
[1, 2]
[1]
[2]

See Mutable default argument for more.

Mutable class attributes

An attribute defined in the class body is shared by all instances. If it is mutable and you mutate it through self, every instance sees the change:

class Cart:
    items = []                  # class attribute: shared by all instances

    def add(self, item):
        self.items.append(item)

c1, c2 = Cart(), Cart()
c1.add("apple")
print(c2.items)

class FixedCart:
    def __init__(self):
        self.items = []         # instance attribute: one list per object

    def add(self, item):
        self.items.append(item)

c1, c2 = FixedCart(), FixedCart()
c1.add("apple")
print(c2.items)
['apple']
[]

With dataclasses, use field(default_factory=list). A plain items: list = [] raises ValueError at class creation, so dataclasses catch this mistake for you.

Storing a caller's object

When an object keeps a reference to a list it was given, the caller can still change it later. Make a defensive copy when you take ownership of data, and hand out immutable views of internal state:

class Account:
    def __init__(self, history):
        self.history = history          # stores a reference to the caller's list

log = ["open"]
acct = Account(log)
log.clear()
print(acct.history)

class SafeAccount:
    def __init__(self, history):
        self._history = list(history)   # defensive copy

    @property
    def history(self):
        return tuple(self._history)     # callers cannot modify internal state

log = ["open"]
acct = SafeAccount(log)
log.clear()
print(acct.history)
[]
('open',)

Copying: shallow and deep

When you really need an independent object, make a copy explicitly. There are two kinds:

import copy

original = [[1, 2], [3, 4]]

shallow = original.copy()        # same as original[:], list(original), copy.copy(original)
deep = copy.deepcopy(original)

original[0].append(99)
original.append([5])

print(original)
print(shallow)
print(deep)
print(shallow[0] is original[0], deep[0] is original[0])
[[1, 2, 99], [3, 4], [5]]
[[1, 2, 99], [3, 4]]
[[1, 2], [3, 4]]
True False

Appending to original doesn't affect shallow, because they are different lists. But the inner list [1, 2] is shared, so append(99) shows up in both.

The same applies to dicts. dict(d), {**d}, d.copy() and d | {} are all shallow:

config = {"name": "app", "tags": ["web"]}

copy1 = dict(config)
copy2 = {**config}
copy3 = config | {}

copy1["name"] = "other"     # top-level change: only copy1 is affected
copy2["tags"].append("api") # nested change: shared by all of them

print(config)
print(copy1)
print(copy3)
{'name': 'app', 'tags': ['web', 'api']}
{'name': 'other', 'tags': ['web', 'api']}
{'name': 'app', 'tags': ['web', 'api']}

A shallow copy is enough when the items are immutable (a list of numbers or strings). Use copy.deepcopy() for nested mutable data. It handles cycles and shared references, but it is much slower and copies everything reachable, so don't use it on objects that hold files, sockets or locks. Classes can customize both kinds of copying with __copy__ and __deepcopy__. More details in Performing a shallow copy and Performing a deep copy.

Immutable containers holding mutable objects

A tuple is immutable: you can't add, remove or replace its items. But if an item is itself mutable, that item can still change:

t = (1, [2, 3])
t[1].append(4)
print(t)

try:
    hash(t)
except TypeError as e:
    print("TypeError:", e)

print(hash((1, (2, 3))) == hash((1, (2, 3))))
(1, [2, 3, 4])
TypeError: unhashable type: 'list'
True

A tuple is hashable (and so usable as a dict key or set member) only if all its items are hashable.

A well-known oddity follows from this. t[1] += [4] first extends the list in place (which works), then tries to store the result back into the tuple (which fails). So you get an exception and the change:

t = (1, [2, 3])
try:
    t[1] += [4]
except TypeError as e:
    print("TypeError:", e)
print(t)
TypeError: 'tuple' object does not support item assignment
(1, [2, 3, 4])

Closures capture variables, not values

A nested function or lambda refers to the variable in the enclosing scope, not to its value at the time the function was created. The lookup happens when the function is called:

callbacks = [lambda: i for i in range(3)]
print([f() for f in callbacks])

callbacks = [lambda i=i: i for i in range(3)]
print([f() for f in callbacks])
[2, 2, 2]
[0, 1, 2]

All three lambdas share the one variable i, which is 2 when the loop ends. The fix binds the current value as a default argument, since defaults are evaluated when the function is created. functools.partial works too. For how names are resolved, see Variable Scope and Binding.

del removes names, not objects

del name removes the binding between a name and an object. The object itself lives on as long as something else refers to it. CPython frees an object as soon as its reference count drops to zero:

import sys

a = [1, 2, 3]
b = a
print(sys.getrefcount(a))   # a, b and the temporary argument

del a
print(b)
print(sys.getrefcount(b))
try:
    print(a)
except NameError as e:
    print("NameError:", e)
3
[1, 2, 3]
2
NameError: name 'a' is not defined

The exact counts are a CPython detail and can change between versions. Don't write code that depends on them.

A weak reference refers to an object without keeping it alive. This is useful for caches and observer lists:

import weakref

class Node:
    def __del__(self):
        print("Node freed")

n = Node()
ref = weakref.ref(n)
print(ref() is n)

del n            # last strong reference gone
print(ref())
True
Node freed
None

See Reference Counting and Garbage Collection for how memory is reclaimed, including reference cycles.

Avoiding shared mutable state

Aliasing is only a problem when something gets mutated. The fewer shared mutable objects you have, the fewer surprises you get.

Use immutable value objects. A frozen dataclass can't be modified, and dataclasses.replace() gives you a modified copy:

from dataclasses import dataclass, replace

@dataclass(frozen=True)
class Point:
    x: int
    y: int

p = Point(1, 2)
q = replace(p, y=5)     # a modified copy; p is unchanged
print(p, q)

try:
    p.x = 10
except AttributeError as e:
    print(type(e).__name__, e)
Point(x=1, y=2) Point(x=1, y=5)
FrozenInstanceError cannot assign to field 'x'

Pass immutable snapshots or read-only views when the receiver shouldn't change your data:

from types import MappingProxyType

_settings = {"debug": False}
settings = MappingProxyType(_settings)   # read-only view

try:
    settings["debug"] = True
except TypeError as e:
    print("TypeError:", e)

_settings["debug"] = True                # the view reflects the owner's changes
print(settings["debug"])

def process(items: tuple[int, ...]) -> int:
    return sum(items)

data = [1, 2, 3]
print(process(tuple(data)))              # pass an immutable snapshot
TypeError: 'mappingproxy' object does not support item assignment
True
6

Type hints help as well. Annotate a parameter as collections.abc.Sequence or Mapping instead of list or dict, and a type checker such as mypy or pyright will flag any attempt to mutate it inside the function.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents