Sub topic 1
Names, objects, and assignment
Prerequisites
This chapter assumes you can run Python code in a script or the interactive interpreter. It also assumes you can use print() to show values and know what a program and a statement are. You do not need to know about functions, classes, or loops.
The working model: names point to objects
In Python, an assignment does not copy a value into a box. It binds a name to an object. An object is a value that lives in memory, such as the integer 3 or the string "Ada". A name is a label that refers to one object at a time.
count = 3This statement does two things. Python creates (or finds) an int object with the value 3. Then it binds the name count to that object. If you later write count = "three", Python binds the same name to a different object. The old object is not changed.
Many languages, such as C, treat a variable as a fixed box with a declared type. Python has no declarations. A name exists once something is assigned to it.
Choosing valid and readable names
A name must follow these rules:
- It can contain letters, digits, and underscores.
- It cannot start with a digit.
- It is case sensitive, so
totalandTotalare different names. - It cannot be a reserved keyword such as
if,for,class, orNone.
Python also accepts many non-ASCII letters in names, but most teams stay with ASCII.
Conventions are not enforced by the interpreter, but nearly all Python code follows PEP 8, the community style guide:
| Kind of name | Convention | Example |
|---|---|---|
| Variables and functions | `snake_case` | `item_count` |
| Constants (by convention only) | `UPPER_SNAKE_CASE` | `MAX_RETRIES` |
| Classes | `CapWords` | `OrderLine` |
| Internal use | leading underscore | `_cache` |
Choose names that say what the value means. elapsed_seconds is better than t, and user_count is better than n2.
A common error is shadowing a built-in name. Python does not stop you from writing list = [1, 2] or str = "x". After that, list(...) and str(...) in the same scope no longer do what you expect.
import keyword
print(keyword.iskeyword("class"))
print(keyword.iskeyword("Class"))
total_price = 10
Total_price = 20
print(total_price, Total_price)This prints True, False, and then 10 20, because Class is not a keyword and the two price names are distinct.
Dynamic typing and checking types with type()
Python is dynamically typed. The type belongs to the object, not to the name. A name can refer to an integer now and a string later. The built-in type() reports the type of the object that the name currently refers to.
count = 3
price = 4.5
name = "Ada"
print(type(count), type(price), type(name))
count = "three"
print(type(count))The output is:
<class 'int'> <class 'float'> <class 'str'>
<class 'str'>Python is still strongly typed. It does not silently mix incompatible types. "3" + 4 raises TypeError instead of guessing. Dynamic means types are checked when code runs, not before. Strong means the checks still happen.
Rebinding a name to a different type is legal but often a sign of unclear code. A name that holds a number in one place and text in another is hard to read. Prefer one meaning per name. Optional type hints such as count: int = 3 document your intent for readers and tools. The interpreter does not enforce them at run time.
To test a type inside a program, isinstance(count, int) is usually better than type(count) == int. It also accepts subclasses, which matters for bool (covered in a later chapter).
Identity, equality, and mutability
Every object has an identity, a value, and a type. These ideas are separate:
==compares values.iscompares identity, which means "are these the same object?"id(obj)returns a number that identifies the object while it exists.
Objects are either immutable (cannot change after creation) or mutable (can change in place). Integers, floats, strings, and tuples are immutable. Lists, dictionaries, and sets are mutable. This difference decides what assignment between two names means in practice.
x = 5
y = x
y += 1
print(x, y)
a = [1, 2]
b = a
b.append(3)
print(a)
print(a is b)The output is:
5 6
[1, 2, 3]
TrueHere is why:
y = xbindsyto the sameintobject asx.y += 1cannot change an immutable int. It computes a new object, 6, and rebindsyto it.xstill refers to 5.b = abindsbto the same list.b.append(3)changes that one list in place, soashows the change.
Nothing was copied in either case. The difference is that the list can be changed in place and the integer cannot.
To get an independent list, make a copy explicitly:
a = [1, 2]
b = a.copy()
b.append(3)
print(a, b)
print(a == b, a is b)This prints [1, 2] [1, 2, 3] and then False False.
How the interpreter handles a name
You can inspect the bindings in a scope. At module level, they live in a dictionary returned by globals().
level = 1
print("level" in globals())
del level
print("level" in globals())This prints True then False. del level removes the binding, not the object. An object is freed only when no names or other references point to it. CPython (the standard implementation) does this with reference counting. That is why del on a name is not the same as deleting the data.
Using a name that has no binding raises NameError:
try:
print(missing_name)
except NameError as e:
print("NameError:", e)This prints NameError: name 'missing_name' is not defined. The usual causes are a typo, using the name before assigning it, or assigning it in a different scope.
Where names get bound
Plain = is the most common binding, but many statements bind names:
for item in items:bindsitemon each pass.import mathbindsmath.def greet(): ...bindsgreetto a function object.class Point: ...bindsPointto a class object.with open(path) as f:bindsf.
Seeing all of these as "bind a name to an object" explains why a later def or import with the same name replaces an earlier binding silently.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Changing one list changes another | Two names refer to the same mutable object | Copy with `.copy()` or `list(a)` |
| `TypeError: 'list' object is not callable` | A built-in name was shadowed | Rename the variable, restart the session |
| `NameError` | Name used before it is bound, or misspelled | Check spelling and order of statements |
| `SyntaxError` on an assignment | Invalid name, such as `2fast` or `class` | Follow the naming rules |
| `is` gives surprising results | Identity compared instead of value | Use `==` |
A subtle case is a chained assignment such as a = b = []. It binds both names to one list, not two. Write a = [] and b = [] on separate lines if you need two lists.
a = b = []
a.append(1)
print(b)
c = []
d = []
c.append(1)
print(d)This prints [1] and then [].
Summary
- Assignment binds a name to an object. It never copies the value.
- Types belong to objects. A name can be rebound to an object of any type.
==compares values,iscompares identity, andtype()reports the type of the current object.- Rebinding a name affects only that name. Mutating a shared object is visible through every name that refers to it.
- Names follow strict rules and PEP 8 conventions. Do not shadow built-ins.
Exercise
Predict the output of this code, then explain why. p = [10, 20] q = p q = q + [30] r = p r.append(40) print(p, q, r)
Show answer
It prints [10, 20, 40] [10, 20, 30] [10, 20, 40]. The line q = p binds q to the same list as p. The line q = q + [30] builds a new list and rebinds q, so p is untouched. The line r = p binds r to the original list, and r.append(40) mutates it in place, so both p and r show the 40.
Exercise
A learner writes max = 10 near the top of a script. Later, max(3, 8) raises TypeError: 'int' object is not callable. What happened, and what is the fix?
Show answer
The assignment bound the name max to the integer 10 in the script's scope, hiding the built-in function max. Calling max(3, 8) then tries to call an int. Rename the variable to something like max_value. In an interactive session, del max removes the shadowing binding and restores access to the built-in.
Exercise
Why is if value is None: correct, while if count is 0: is a bad habit?
Show answer
None is a singleton, so there is exactly one None object and is reliably tests for it. Integers are ordinary values, and whether two equal ints are the same object depends on interpreter optimizations. Use count == 0 to compare numeric values.