Sub topic 1
Names, Objects, and Assignment
Prerequisites
This chapter assumes you can run Python code in a script or the interactive interpreter, use print() to show values, and know what a statement is. No other Python knowledge is needed.
Assignment binds a name to an object
In many languages, a variable is a box that holds a value. Python works differently. Every value is an object living in memory, and a name is a label that refers to that object. The statement count = 3 means "make the name count refer to the integer object 3."
This model explains behavior that otherwise looks odd. Assigning one name to another does not copy anything. It makes a second label for the same object.
Dynamic typing
A name has no fixed type. The object has the type. type() reports the type of the object a name currently refers to, and you may rebind the name to an object of a different type.
count = 3
price = 4.5
name = "Ada"
print(type(count), type(price), type(name))
count = "three"
print(type(count))The first line prints <class 'int'> <class 'float'> <class 'str'>. After rebinding, count refers to a string, so the last line prints <class 'str'>. Python allows this, but reusing one name for unrelated types makes code harder to read.
Rebinding versus mutating
Two different operations can look alike:
- Rebinding points a name at a different object. Other names are unaffected.
- Mutating changes the object itself. Every name that refers to it sees the change.
x = 5
y = x
y += 1
print(x, y)
a = [1, 2]
b = a
b.append(3)
print(a)
print(a is b)The first part prints 5 6. Integers cannot be changed, so y += 1 creates a new integer and rebinds y. The name x still refers to 5. The second part prints [1, 2, 3] and True. A list can be mutated, and a and b refer to one list, so append through b is visible through a.
Identity and equality
Python has two kinds of comparison:
| Operator | Question it answers |
|---|---|
| `==` | Do the two objects have equal values? |
| `is` | Are the two names bound to the very same object? |
Use == to compare values. Reserve is for checks such as value is None. The function id() returns a number identifying an object for its lifetime, and a is b is true when both names give the same id().
If you want an independent list, copy it explicitly, for example with b = a.copy().
Common errors
- Expecting
b = ato copy a mutable object, then being surprised when changes tobappear ina. - Using
isto compare numbers or strings. It may seem to work for small values, but that is an implementation detail. Use==. - Assuming
y += 1changesxbecausey = xcame first. For integers it does not.
Exercise
After running p = [10], q = p, q.append(20), r = 7, s = r, s += 1, what are the values of p and r, and is p is q true?
Show answer
p is [10, 20] because q refers to the same list and append mutated it. r is still 7 because s += 1 rebinds s to a new integer. p is q is True.