Skip to content
Fullstack Launchpad

Python Objects and the Data Model #1.4

Assignment binds a name to an object. When two names refer to the same list, changes made through one name are visible through the other.

By Published Updated 8 min readPython for Engineers Switching Languages

Objects and the data model

What does this code print?

python
a = [1, 2]
b = a
b.append(3)
print(a)
# prints: [1, 2, 3]

The change went through b, yet a changed too. The reason: Python keeps two things apart.

  • An object is the actual data in memory, here a list.
  • A name (a variable) such as a or b is only a label attached to an object. b = a does not copy the list; it attaches the label b to the same list.

Two names, a and b, point at one list; after b.append(3) both see [1, 2, 3]

The whole lesson builds on this picture. Each row below is one consequence of it, with a short example:

SectionExampleResult
Names and objectsb = aa and b label one list
Mutation and rebindingb.append(3), then b = [4]a sees the 3, but not [4]
is and ==[1] == [1], [1] is [1]True, False
Shallow and deep copiescopy.copy(a), copy.deepcopy(a)the inner list is still shared, or fully separate
Default argumentsdef f(x=[]):every call of f() shares one list
dict keys{[1, 2]: "x"}TypeError: a list cannot be a key
Dunder methodslen(a)Python calls a.__len__()

How some other languages compare

OperationJS / TSJavaGo
Sharing a sequenceAssigning an array shares itAssigning an array reference shares itAssigning a slice shares its underlying array
Comparing sequences=== tests array identity== tests array identity== cannot compare two slices
Default valuesEvaluated each time neededNo parameter defaultsNo parameter defaults

Names and objects

Every value in Python is an object, including functions and types themselves, such as list. Each object has an identity (which distinguishes it from every other live object), a type (which defines the operations it supports) and a value (for example, the contents of a list).

The parts of a = [1, 2]

PartMeaning
aName bound to the result on the right
=Evaluate the right side, then bind the name on the left
[1, 2]Create a two-item list with square brackets and commas between items
python
a = [1, 2]
print(type(a))
# prints: <class 'list'>
print(type(print))
# prints: <class 'builtin_function_or_method'>

Mutation and rebinding

In the example below, b = a binds the name b to the existing list. Two names referring to the same object is called aliasing. The dot in b.append(3) accesses the list's append method, which adds 3 to the end of that mutable list.

python
a = [1, 2]
b = a
b.append(3)
print(a)
# prints: [1, 2, 3]
print(b)
# prints: [1, 2, 3]
b = [4]
print(a)
# prints: [1, 2, 3]
print(b)
# prints: [4]

Both a and b see [1, 2, 3] after b.append(3) because the shared list changed. b = [4] binds b to a new list. The name a still refers to the original list.

A string cannot be changed in place: name + "-v2" builds a new string, and assignment rebinds name. The name original still refers to the original string.

python
name = "Orbit"
original = name
name = name + "-v2"
print(original)
# prints: Orbit
print(name)
# prints: Orbit-v2

Identity and value equality

Shared data for the table and example below is a = [1, 2], b = [1, 2] and alias = a.

WriteMeaning
a == bCompare values. The lists have equal corresponding elements, so this gives True
a is bCompare identity. The two list literals create separate objects, so this gives False
a is aliasBoth names refer to one list, so this gives True
id(a) == id(alias)The same object has the same identifier, so this gives True
python
a = [1, 2]
b = [1, 2]
alias = a

print(a == b)
# prints: True
print(a is b)
# prints: False
print(a is alias)
# prints: True
print(id(a) == id(alias))
# prints: True

Shallow and deep copies

Shared data for the table is a = [[1, 2]], with import copy to load the copy module from Python's standard library. The outer list has one item, the list [1, 2].

WriteMeaning
copy.copy(a)Shallow copy of list a
list(a)New list from the existing items in a
a[:]Slice the whole list to make a shallow copy
copy.deepcopy(a)Deep copy, including the nested list in the example

All three shallow-copy operations make a new outer list. Appending [] to shallow leaves a as it was. Mutating the inner list through sliced[0] changes what a sees, while deep has its own inner list.

python
import copy

a = [[1, 2]]
shallow = copy.copy(a)
listed = list(a)
sliced = a[:]
deep = copy.deepcopy(a)

print(shallow is a)
# prints: False
print(shallow[0] is a[0])
# prints: True
print(listed[0] is a[0])
# prints: True
print(sliced[0] is a[0])
# prints: True

shallow.append([])
print(a)
# prints: [[1, 2]]
sliced[0].append(3)
print(a)
# prints: [[1, 2, 3]]
print(deep)
# prints: [[1, 2]]

Shared mutable defaults

The parts of def f(x=[]):

PartMeaning
def fDefine a function named f
(x=[])When the argument is omitted, parameter x receives the default list
:Open the function body. By convention its lines are indented by four spaces

Python creates the default list once when the def statement runs. All three calls to f() below append to the same list.

python
def f(x=[]):
    x.append("Orbit")
    return x

print(f())
# prints: ['Orbit']
print(f())
# prints: ['Orbit', 'Orbit']
print(f())
# prints: ['Orbit', 'Orbit', 'Orbit']

Use x=None as the default. if x is None: opens an indented block that creates a fresh list when x is None. A caller can supply a list, in which case the function appends to that list.

python
def f(x=None):
    if x is None:
        x = []
    x.append("Orbit")
    return x

print(f())
# prints: ['Orbit']
print(f())
# prints: ['Orbit']
print(f())
# prints: ['Orbit']

provided = []
print(f(provided) is provided)
# prints: True
print(provided)
# prints: ['Orbit']

Hashability and dict keys

A dict stores key-value pairs. In CPython, a widely used implementation of Python, both dict and set use hash tables. To look up a key, Python computes the key's hash (the integer returned by hash()) to jump straight to where it should be, then uses == to confirm the key. That is why lookup is O(1) on average (read “big O of one”: just as fast with 10 entries as with a million).

A hashable object has a hash that never changes during its lifetime. If a key changed its contents after going into a dict, its hash would change and the dict would look in the wrong place. That is why mutable types such as list, dict and set cannot be keys.

The parts of scores[("Orbit", 1)]

Shared data is scores = {("Orbit", 1): 10}.

PartMeaning
scoresDict with one key-value pair from the shared data
("Orbit", 1)Tuple with a string and an integer. Both items are hashable
[...]Look up the key inside the brackets. The result here is 10
python
scores = {("Orbit", 1): 10}
print(scores[("Orbit", 1)])
# prints: 10

A one-item tuple is written (items,), with a comma before the closing parenthesis. The tuple below keeps the same list in that position. The list can still change, and using the tuple containing it as a key raises an error.

python
items = [1]
key = (items,)
items.append(2)
print(key)
# prints: ([1, 2],)
scores = {key: 10}
# error: TypeError: unhashable type: 'list'

Dunder methods

The data model is the set of rules linking Python syntax and built-in functions to each type's behaviour. Special methods with two underscores on each end of the name are called dunder methods, short for double underscore.

Shared data is a = [1, 2], b = [1, 2] and name = "Orbit".

WriteMeaning
len(a)Uses __len__ to get the length. Result 2
a == bUses __eq__ to test equality. Result True
repr(name)Uses __repr__ to get a representation for engineers. Result 'Orbit'
python
a = [1, 2]
b = [1, 2]
name = "Orbit"

print(len(a))
# prints: 2
print(a == b)
# prints: True
print(repr(name))
# prints: 'Orbit'

Key takeaways

  • Binding a new name to an existing list creates an alias. Mutating the list through one name changes what the other name sees.
  • is asks “same object?” and == asks “equal?”. id() gives an identifier for the object's lifetime.
  • A shallow copy owns its outer container. A deep copy of a nested list copies the inner lists too.
  • A default value is evaluated when Python defines the function. Use None to create a fresh list in each call that needs the default.
  • A dict key must be hashable. A tuple can serve as a key only if all its items are hashable.
  • __len__, __eq__ and __repr__ connect familiar operations to the behaviour of a type.

Sources