🎓 A1Learner
🔍

Python Names, Objects & References

A name is a label stuck on an object. An object is the real value in memory.

A second name for one list

b = a does not make a new list. It sticks a second label on the same list.

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

Change it through either name

There is only one list. A change through b shows up through a.

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

Ask if names share an object

is compares the objects themselves. id() gives an object's identity number, so equal numbers mean one object.

a = [1, 2, 3]
b = a
print(a is b)
print(id(a) == id(b))

Equal is not the same

Two separate lists can hold the same values. They are equal, but they are not the same object.

a = [1, 2, 3]
c = [1, 2, 3]
print(a == c)
print(a is c)

Numbers behave differently

Numbers are immutable, so they cannot change in place. y = y + 1 makes a new number and moves the y label.

x = 5
y = x
y = y + 1
print(x)
print(y)

Arguments share the object

A function gets a label on your object. Changing a mutable object inside changes it outside too.

def add_item(items):
    items.append(99)

nums = [1, 2]
add_item(nums)
print(nums)

Example

shopping = ["milk", "eggs"]
backup = shopping
backup.append("bread")
print(shopping)
print(backup)
print(backup is shopping)

Key points

  • Object: the real value in memory, such as a list or a number
  • Reference: a link from a name to an object
  • Alias: a second name for the same object
  • Assignment never copies an object.
  • It only sticks a label on it.
  • Use is to ask if two names point to the same object
  • Use == to ask if two objects hold equal values
  • Mutable: an object you can change in place, like a list
  • Immutable: an object you cannot change in place, like a number

In this example, shopping is a list with two items. backup = shopping sticks a second label on that same list. It does not copy the list. So backup.append("bread") changes the one shared list. Both names now print all three items. The last line proves the point with is. Both names point to the same object, so it prints True. Predict this before you run code like it. If you wanted a separate list, you would need a real copy.

Note

Function arguments work by assignment.

The parameter becomes a new label on the caller's object.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

After a = [1, 2], then b = a, then b.append(3), what is a?