Python: the essentials

What every reader of the Python pages needs first: names and objects, syntax as method calls on one interpreter, the traps that cut across the language, how to choose a tool for a job, and the map of the four child pages. Every output is a real run on CPython 3.14.8 on an Apple M1 Pro. Data as of October 2026. Reading: 12 min, plus 1 in closed details.

The idea in one screen

In Python a name is only a reference to an object, and every piece of syntax is a method call on the object's type, run as bytecode by one interpreter that counts references to each object and, in the default build, lets one thread run at a time. Almost every surprise a working Python programmer meets follows from that sentence.

Fig. 1 follows one small program, the three lines of section 2's figure saved as app.py, from install to run. Steps 3 to 7 are the five facts behind almost every surprise; each names the child page that owns it and links that page's own figure. The instruction names and reference counts drawn are this page's real run on CPython 3.14.8 (Fig. 2).

  1. One program, start to finish. Before it runs, uv installs what it imports into an environment and a type checker reads its hints. Then CPython compiles it to bytecode, one loop runs that bytecode, every value lives as an object on the heap, and in the default build one thread at a time holds the loop.
  2. Installed: the environment comes from a lock. pyproject.toml says what you asked for, uv.lock what one resolution picked, and uv sync makes .venv match the lock exactly, so a package added by hand with pip install is gone after the next sync. Owner: Python: typing, uv, packaging and the toolchain, whose Fig. 2 replays a real uv session.
  3. Checked: hints are for tools. Annotations are not checked when the program runs; a type checker (ty, mypy, pyright or pyrefly) reads them before, in the editor or in CI, and Python itself never does. Owner: the toolchain page, whose Fig. 1 runs five deliberate mistakes past two checkers and past Python.
  4. Compiled and run: one loop runs bytecode. CPython compiles the file to bytecode, and a loop written in C runs it one instruction at a time: y = x is LOAD_NAME then STORE_NAME, y.append(3) finds the method with LOAD_ATTR, and + is BINARY_OP. Because every operation goes through this loop, on arrays of a thousand elements and up a Python loop was 10 to 16 times slower than one NumPy call: profile first, then move the loop out of Python. Owner: Python: CPython internals and performance, whose Fig. 3 steps one function through the loop.
  5. Names point at objects. Every value is an object on the heap that knows its type and how many references point at it; a name is only an entry in a namespace. Assignment never copies: y = x gives one object a second name and its reference count goes from 1 to 2, so mutation through either name is visible through both. Copies happen only when you ask (.copy(), copy.deepcopy, a slice). Section 2 below; what each object costs and how counting frees it are the internals page's Fig. 4 and Fig. 5.
  6. Syntax calls methods on the type. y.append(3) runs type(y).append(y, 3), found on list, so x sees the change; x + [4] runs list.__add__, which builds a new list with 1 reference. len(x), for, ==, with and x.attr are each a fixed lookup of a double-underscore ("dunder") method on the type, with documented fallbacks. Laziness is a protocol too (an iterator is any object with __next__; a generator is a function that pauses at yield), and def and class are statements that create objects at run time, which is why decorators, closures and descriptors work the way they do. Owner: Python: the data model and protocols, whose Fig. 1 climbs each lookup and Fig. 7 the attribute lookup.
  7. One thread runs bytecode at a time. In the default build the GIL lets one thread at a time run the loop. The GIL makes threads useful for waiting, not for computing; processes or native code compute in parallel; asyncio runs thousands of waits on one thread, provided nothing blocks it. Owner: Python: concurrency, asyncio and the GIL, whose Fig. 1 shows who runs bytecode six ways and Fig. 3 replays a real event loop.

You need: to write everyday Python. Nothing else on this page is assumed. How Python compares with C++, Rust and TypeScript (types, memory, errors, concurrency, speed), with the same program written in all four, is the parent page Topic: programming-languages.

Name
an entry in a namespace (a dict-like table from strings to objects); it holds a reference, never a value.
Object
a block of memory that knows its type, its value and how many references point at it.
Alias
a second name for the same object.
Mutable
can change after it is made (list, dict, set, most classes); immutable types (int, float, str, tuple, frozenset, bytes) never do.
Special ("dunder") method
a double-underscore method such as __add__ that syntax calls on the type.
Bytecode
the instructions CPython compiles your code to and runs one at a time in a loop written in C.
GIL
the global interpreter lock: in the default build only the thread holding it runs bytecode.

1. Five things the runs showed

Each is measured, with its script and output, on the child page named.

FindingMeasured on
A shared dict updated from threads with no lock lost tokens even with the GIL (3 of 5 runs on 3.14); without the GIL every run lost 24k to 36k. A lock fixed both.Concurrency, asyncio and the GIL, section 3
One blocking time.sleep inside async code delayed another task by 100 ms; asyncio.to_thread removed the delay.Concurrency, asyncio and the GIL, section 2
A generator over a million lines peaked at 1.1 KiB; the same work as a list peaked at 106 MiB.The data model and protocols, section 3
Lazy imports (3.15) took a small CLI from 100 ms to 26 ms at start-up, and from 268 to 64 imported modules.CPython internals and performance, section 7
An extension that does not declare free-threading support silently turns the GIL back on when imported.Concurrency, asyncio and the GIL, section 3

2. Names, objects and references

A Python object is a block of memory that knows its type, its value and how many references point at it. A name (a variable) is an entry in a namespace, a dict-like table from strings to objects. Assignment, b = a, writes a second entry pointing at the same object. Nothing is copied. Two names for one object are aliases.

Whether aliasing matters depends on mutability: whether the object can change after it is made. Lists, dicts, sets and most of your own classes are mutable. Ints, floats, strings, tuples, frozensets and bytes are immutable: every "change" builds a new object and rebinds the name. Predict what b holds before you open the answer:

Aliasing
a = [1, 2]
b = a
a += [3]
print(b)
Predict the output, then reveal
real output, Python 3.14.8 (outputs/q_drills.json)
[1, 2, 3]
n1_alias.py
a = [1, 2]
b = a              # a second name for the same list object
b.append(3)
print(a, a is b)

x = 10
y = x
y += 1             # ints are immutable: += builds a new int and rebinds y
print(x, y)
real output, Python 3.14.8
[1, 2, 3] True
10 11

Two questions about two names: equal, or the same object?

a == b asks "equal values?" and calls __eq__; a is b asks "the same object?" and compares identities (the address, in CPython). Use is only for singletons such as None; for everything else it answers a question you did not mean to ask.

n2_identity.py
a = [1, 2]
b = [1, 2]
print(a == b, a is b)          # equal values, two objects

x, y = 256, int("256")
print(x is y)                  # CPython keeps one shared object for -5..256
x, y = 257, int("257")
print(x is y)                  # outside that range: two objects
print(x == y)                  # == is the question you meant to ask
Predict the output, then reveal
real output, Python 3.14.8
True False
True
False
True
is with strings
import sys
a = 'model'
b = ''.join(['mod', 'el'])
print(a == b, a is b, a is sys.intern(b))
Predict the output, then reveal
real output, Python 3.14.8 (outputs/q_drills.json)
True False True

The 256 against 257 split is an implementation detail: "The current implementation keeps an array of integer objects for all integers between -5 and 256" (C API: integer objects). Strings are the same story: some are interned (one shared object), and sys.intern forces it. Code that relies on it works in tests with small numbers and breaks in production with large ones. Why the cache exists, and what each object costs, is CPython internals and performance, section 2.

The default argument that remembers

A function's default values are evaluated once, when def runs, and stored on the function object; a mutable default is therefore one object shared by every call that does not pass its own. The fix is None as the default and a new list inside.

Default argument
def f(x, seen=[]):
    seen.append(x)
    return len(seen)
print(f('a'), f('b'), f('c', []), f('d'))
Predict the output, then reveal
real output, Python 3.14.8 (outputs/q_drills.json)
1 2 1 3

A call that passes its own list leaves the shared one alone; the next call that relies on the default picks up where the shared list left off. Copies (shallow against deep, the nested-list trap), what a function receives when you pass it an object, and += as a method call are the data model and protocols, section 2, with Fig. 3 drawn from a recorded run of CPython's real objects.

Fig. 2 · three lines: the first copies nothing, the second changes the object both names see, the third calls a method that builds a new one

1. y = x
namesobjects (on the heap) xy [1, 2]list, refs 2 No method runs (bytecode STORE_NAME):a second name, refs 1 to 2; nothing copied
2. y.append(3)
namesobjects xy [1, 2, 3]same list, refs 2 type(y).append(y, 3)LOAD_ATTR finds append on list; x sees it
3. z = x + [4]
namesobjects xyz [1, 2, 3]unchanged, refs 2 [1, 2, 3, 4]new list, refs 1 type(x).__add__(x, [4])BINARY_OP (+): a new object; x unchanged

Blue is the method looked up on the type, the thing to notice: the name never decides what + or .append does; the object's type does. Reference counts, the method each line called and the bytecode names are from the real run below. The same three lines are steps 4 to 6 of Fig. 1.

The real run behind the figure (h1_hero.py: reference counts, the methods called, the bytecode)
h1_hero.py
"""The hero of "Python: the essentials": three lines, and what each one does to names, objects and methods."""
import dis, sys

x = [1, 2]
print("refs to the list after x = [1, 2]:", sys.getrefcount(x) - 1)   # getrefcount counts its own argument; subtract it
y = x
print("after y = x:      y is x ->", y is x, "| refs:", sys.getrefcount(x) - 1)
y.append(3)
print("after y.append(3): x ->", x)
z = x + [4]
rz = sys.getrefcount(z) - 1   # measured before print, whose argument tuple would hold one more
print("after z = x + [4]: x ->", x, "| z ->", z, "| z is x ->", z is x, "| refs to z:", rz)
print("x + [4] calls      ->", type(x).__add__)
print("y.append is found on ->", type(y).append)

print("\nbytecode of the three lines (dis, CPython", sys.version.split()[0] + "):")
dis.dis(compile("y = x\ny.append(3)\nz = x + [4]", "<hero>", "exec"))
real output, Python 3.14.8
refs to the list after x = [1, 2]: 1
after y = x:      y is x -> True | refs: 2
after y.append(3): x -> [1, 2, 3]
after z = x + [4]: x -> [1, 2, 3] | z -> [1, 2, 3, 4] | z is x -> False | refs to z: 1
x + [4] calls      -> <slot wrapper '__add__' of 'list' objects>
y.append is found on -> <method 'append' of 'list' objects>

bytecode of the three lines (dis, CPython 3.14.8):
  0           RESUME                   0

  1           LOAD_NAME                0 (x)
              STORE_NAME               1 (y)

  2           LOAD_NAME                1 (y)
              LOAD_ATTR                5 (append + NULL|self)
              LOAD_SMALL_INT           3
              CALL                     1
              POP_TOP

  3           LOAD_NAME                0 (x)
              LOAD_SMALL_INT           4
              BUILD_LIST               1
              BINARY_OP                0 (+)
              STORE_NAME               3 (z)
              LOAD_CONST               1 (None)
              RETURN_VALUE

3. Traps that catch experienced people

Every trap below starts at one stop of Fig. 1 (the "Step" column); each is shown with its real output on the page named.

TrapWhyStepShown on
Mutable default argumentEvaluated once at def5, 6section 2 above; data model s2, n4_args
is on numbers and strings "working"Small-int cache and interning are implementation details5section 2 above; internals s2
[[0] * n] * mRepeats one inner list5data model s2, n3_copy
Modifying a list or dict while iterating itSkips items (list) or raises RuntimeError (dict)5, 6data model s2, n6_iter_mutate
Mutable class attribute shared by all instancesLookup falls through to the class6data model s5, c5_classattr
Late binding in closures: [lambda: i for i in range(3)] all return 2Closures capture variables, not values6data model s4, f1_closure
A generator consumed twiceIterators are single-use6data model s3, g1_protocol
groupby on unsorted dataGroups runs, not keys6data model s3, g6_itertools
Bare except: or except BaseExceptionCatches Ctrl-C and cancellation (KeyboardInterrupt is not an Exception, so except Exception lets it through)6data model s6, e3_hierarchy
return in finallyDiscards the exception (3.14 warns)6data model s6, e4_finally
Threads for CPU work in the default buildThe GIL7concurrency s1, k1_gil
A blocking call inside async defFreezes every task7concurrency s2, Fig. 3
Swallowing CancelledErrorThe task reports success; timeouts break7concurrency s2, a4_cancel
Trusting a type hint at run timePython never checks it; only a checker in CI does3toolchain s1
pip install inside a uv projectInstalls outside the lock; the next uv sync removes it2toolchain s4
Naming your file json.py or random.pyThe script's folder comes first on sys.path, so it shadows the standard library module2sys.path docs
Set orderingDicts keep insertion order (a language guarantee since 3.7); sets do not6What's new in 3.7
0.1 + 0.2 != 0.3, round(2.5) == 2Binary floating point; round-half-to-even4internals s2; Numerical computing

"Step" is the stop in Fig. 1 where the trap starts: 2 installed, 3 checked, 4 run by CPython (the internals page), 5 names, 6 methods on the type, 7 one thread. "s2" means that page's section 2.

4. Choosing: which tool for which job

The one decision that cuts across all four children: where the time goes decides the tool.

Your situationUseWhyGo deeper
Many network calls (an LLM API fan-out)asyncio, or threadsThe time is waiting, which the GIL never blockedconcurrency s2, s5
CPU-bound pure Python, dependencies all portedthreads on the free-threaded buildShared memory, no picklingconcurrency s3
CPU-bound pure Python on the normal buildProcessPoolExecutor, or InterpreterPoolExecutor when start-up mattersEach worker has its own GIL; inputs and outputs are pickledconcurrency s1, s4
Numeric arraysNumPy (or PyTorch)The loop runs in C and releases the GIL; neither the JIT nor threads come closeinternals s4, s5
One hot Python loop you cannot vectoriseRust with PyO3 (or C++ with nanobind)Native code, called from Python, built as a wheelRust: speeding up Python with PyO3 and maturin
A CLI that starts slowlylazy import on 3.15, or -X lazy_imports=allStart-up is importsinternals s7
Minimum Python version for new code3.12 for libraries, the newest bugfix line (3.14) for applications3.12 has the modern generic syntax; applications control their runtimeinternals s6
A new project, or a messy oneuv, ruff, a type checker and pytest in CIOne lock file every machine installs from; checks before run timetoolchain

5. The child pages

Each stands alone; read them in any order. Times are each child's own header (230 words a minute), with the closed blocks counted apart.

Python: the data model and protocols

Child page, about 28 min, plus 21 in closed details

Every operator, loop, with block and attribute access is a special method looked up on the type, with fixed fallbacks. Copies and argument passing, iterators and generators, closures and decorators, the MRO, dataclasses, slots, descriptors, exceptions and context managers, with the Data model explorer inline. In 3D: each lookup climbing its stack (Fig. 1), a lazy against an eager pipeline (Fig. 4), the MRO (Fig. 5) and attribute lookup (Fig. 7).

Python: concurrency, asyncio and the GIL

Child page, about 19 min, plus 10 in closed details

One lock decides what threads can do, and asyncio replaces threads with one loop you must never block. Threads against processes measured on both builds, free-threading in practice, subinterpreters, choosing. In 3D: who runs bytecode six ways (Fig. 1) and a real event loop replayed (Fig. 3).

Python: CPython internals and performance

Child page, about 23 min, plus 6 in closed details

CPython is a bytecode interpreter, so speed comes from moving the loop out of Python, and you measure first. Bytecode and the specialising interpreter, what objects cost, profiling, NumPy, the JIT, 3.12 to 3.15, lazy imports. In 3D: a list of floats against one NumPy buffer (Fig. 1), the evaluation loop (Fig. 3), objects to scale (Fig. 4) and reference counting (Fig. 5). Its Version explorer tab answers "Does this run on my version?"

Python: typing, uv, packaging and the toolchain

Child page, about 22 min, plus 15 in closed details

Hints are checked by tools, never at run time, and packaging is four layers that uv collapses into one lock file. The checkers (ty, mypy, pyright, pyrefly) on the same code, uv, ruff, pytest as a tool, wheels and their tags, trusted publishing. In 3D: who reads the hints (Fig. 1), uv's three files (Fig. 2), where an install spends its time (Fig. 3) and a wheel from source to site-packages (Fig. 4).

Elsewhere: the same program in Python, C++, Rust and TypeScript, and the benchmark across them, is Topic: programming-languages. The sibling language pages are C++: the essentials, Rust: the essentials and JavaScript and TypeScript: the essentials.

Every output, error message and number on this page and its children comes from a real run (CPython 3.13.16, 3.14.8, 3.14.8t and 3.15.0rc3 on an Apple M1 Pro, 2026-10-05; this page's three name examples and the hero rerun on 3.14.8 on 2026-10-26, identical where they overlap). This page replaces the old written pages "Python: zero to expert" and "Python: staying current (3.12 to 3.15)"; every claim from them was checked, and the corrections are shown in boxes on the child that owns each subject. Rebuilt on 2026-10-26 as the essentials page of four children, and on 2026-11-07 in the split layout with Fig. 1 (src/README.md says how).