Python has no “simple” values. An integer is an arbitrary-precision object; a string is an object that picks its own representation. From this follow endless arithmetic with no overflow, division that does not work the way it does in C, and the price that makes numpy exist.
import sys
print(sys.getsizeof(0), sys.getsizeof(2**30), sys.getsizeof(2**1000))
print(2**5000 % 1000003)
28 32 160
(instantly, an exact answer)No overflow, no loss of precision — and an object that keeps growing.print(10**23 == int(1e23))
print(10**23)
print(int(1e23))
False
100000000000000000000000
99999999999999991611392Two ways of writing one number give different numbers.print(-7 // 2, -7 % 2)
print(7 // -2, 7 % -2)
-4 1
-4 -1In C and Java the same expressions give -3 and -1. It is not a bug either there or here.import sys
print(sys.getsizeof(""), sys.getsizeof("a"), sys.getsizeof("aa"))
print(sys.getsizeof("é"), sys.getsizeof("😀"))
49 50 51
74 80An ASCII character adds one byte. One non-ASCII character adds twenty-three.From lesson 01 we know: a value is always an object. Here we look at what that means for the two most common types, and what follows from it.
Since a number is an object on the heap anyway, there is no reason to tie it to a machine word. So int in Python is not a 64-bit integer but an array of digits in base 2³⁰, stored in 32-bit words, plus a header and a sign-and-length field.
Two conclusions follow at once. First: overflow does not exist as a phenomenon. Not “big numbers are supported” — there is no upper bound at all, and no second type for big numbers. Second: the size of the object grows with the magnitude — 28 bytes up to 2³⁰, 32 bytes beyond, 160 bytes for 2¹⁰⁰⁰. Snippet A is about this.
Small integers from −5 to 256 are cached 🔧 — and now it is clear why: if every number is an object, the most frequent numbers are better created once at startup. It is an optimization forced by the model, not a decoration.
float lives by different rules, and precision is lost at the borderfloat is an exception to consequence 1: it is an ordinary IEEE 754 double, 64 bits inherited from the hardware. It has about fifteen exact digits, and integers are exactly representable only up to 2⁵³.
Snippet B is exactly about this. 1e23 is a literal of type float, and the representable number closest to 10²³ is not equal to 10²³. int() honestly converts what is there, and you get 99999999999999991611392. Whereas 10**23 is computed in integers and is exact.
The practical rule derives itself: any int → float → int round trip above 2⁵³ loses data silently. No exception, no warning — just a different number.
Snippet C. -7 // 2 is −4 in Python and −3 in C and Java. The divergence is deliberate, and the reason is an invariant Python chose to preserve:
a == (a // b) * b + (a % b)
If // rounds down, the remainder always has the sign of the divisor, and a % n for a positive n always lies in [0, n). That is exactly what is needed for cyclic indices, hash buckets, coordinates on a torus and time arithmetic.
In C, where division truncates toward zero, the remainder can be negative, and you have to write ((i % n) + n) % n. Anyone who has written a ring buffer in C knows this construct. In Python it is never needed — a direct consequence of one decision about rounding.
A string is immutable, so its representation can be chosen once at creation — and Python takes advantage of that. Since PEP 393 a string has three possible forms: 1, 2 or 4 bytes per character, by the highest code point. Plus a separate, even more compact variant for pure ASCII.
Snippet D becomes transparent. An empty ASCII string is 49 bytes of header, and every further ASCII character is exactly one byte. But a single character outside Latin-1 moves the whole string into the four-byte form and adds service fields to the header — hence 80 bytes for a one-character string with an emoji.
The important consequence, the one all this was done for: indexing into a string stays O(1). s[i] is a read at an offset, because all characters within one string have the same width. Python pays with memory in a rare case so that indexing is always cheap.
Since strings are immutable, identical strings need not be duplicated. Python does this automatically for strings that look like identifiers and for literals inside one code object 🔧:
a = "hello"; b = "hello"; a is b
# → True
exec("x = 'hello world!'", ns); exec("y = 'hello world!'", ns)
print(ns['x'] is ns['y'])
# → False
print(sys.intern("".join(["hel","lo"])) is a)
# → True
Hence the final answer to “why does is sometimes work for strings”: because sometimes it is literally one object. And hence sys.intern as a deliberate tool rather than a curiosity; in section 7 it saves a factor of eight.
Big-number arithmetic is not constant-time. Multiplying numbers thousands of bits long is work over all the digits, and it is hundreds of times more expensive than multiplying small ones. Cryptography and combinatorics in Python work because of this, but slowly. In addition, since 3.11 converting very large integers to a string is limited by default — a protection against quadratic parsing, lifted through sys.set_int_max_str_digits.
Interning is not a guarantee 🔧. Exactly which strings are interned has changed between versions and depends on whether it is a literal and whether it looks like an identifier. You can never rely on is for strings, even if it returns True right now.
Exact arithmetic exists, but not by default. decimal.Decimal for money, fractions.Fraction for rationals. Both are ordinary Python objects, that is, slow; they are chosen deliberately, when the cost of an error is higher than the cost of speed.
The same as in lesson 01: a single object model with no primitives. Here you can see how that one decision pays off and what it costs.
It pays off in freedom: since a number is an object anyway, nothing stops it from being as large as you like. Guido deliberately unified int and long in Python 3 — before that there were two, with an automatic transition, and that was exactly the “second set of rules” the model was supposed to get rid of.
It costs memory and speed: 28 bytes and a function call where C has one instruction on a register. That price is precisely what made numpy inevitable — not as an accelerator but as a way to move homogeneous numbers out of the object model into a contiguous buffer.
Choosing a string's representation is the same thing as choosing a dtype in numpy, only automatic. An array does not store small numbers in float64 without need; a string does not store Latin text in four bytes per character. The idea is the same: do not pay for the worst case when the data does not require it, and fix the representation once so that indexed access remains arithmetic on an offset.
The next step of the analogy holds too: just as one float64 in an int8 array forces the type of the whole array up, one character outside Latin-1 raises the width of the whole string.
Questions that come up on their own if you read closely. The answer is under the question.
0.1 + 0.2 != 0.3 — and what does Python have to do with it?Nothing. This is IEEE 754, the very same one as in C, Java, JavaScript and your processor.
float in CPython is C's double, bit for bit. The numbers 0.1 and 0.2 cannot be represented as a finite binary fraction, just as 1/3 cannot be as a decimal one. The sum of their nearest representable approximations gives a number slightly larger than the nearest approximation to 0.3.
from decimal import Decimal
print(Decimal(0.1))
# → 0.1000000000000000055511151231257827021181583404541015625
Python is more honest here than many: since version 3.1 repr prints the shortest string that round-trips back to the same number. That is why you see 0.1 and not 0.10000000000000001 — and at the same time you see 0.30000000000000004 when the difference has crossed that boundary.
What to do about it. For money — decimal.Decimal or integers in the smallest units (cents). For comparisons — math.isclose. For accumulating sums — math.fsum, which compensates for rounding error. A universal “correct float” does not exist in any language.
Because the alternative is silent overflow, and that is the worst class of errors.
In C, signed integer overflow is undefined behaviour altogether; in practice the number simply turns negative and the program carries on with garbage. Python chose “never lose precision”, and this follows directly from R1: since a number is an object with a 24-byte header anyway, adding a variable-length array of digits to it costs almost nothing.
The price is measurable and non-linear. While the number fits into one 30-bit digit, arithmetic takes the fast path. Beyond that, long arithmetic begins:
import timeit
small = "a * b"
print(timeit.timeit(small, "a = 2**20; b = 2**20", number=1_000_000))
print(timeit.timeit(small, "a = 2**5000; b = 2**5000", number=1_000_000))
# a difference of hundreds of times
Where the border is in practice. Cryptography, combinatorics, exact computation — there arbitrary precision is the whole point. Arrays of numbers — there it is harmful, and numpy's answer is fixed width, modular overflow, but 8 bytes instead of 28 and vector instructions. Lesson 15 is entirely about this border.
3.11 also added a limit on the length of the decimal representation (4300 digits by default) — a protection against an attack in which int(string) on megabyte-sized input takes a service down with a quadratic algorithm.
Because interning trades memory for time, and the trade is far from always a good one.
To intern a string you have to hash all of it and look it up in a global table. For a string that occurs once that is a pure loss: you paid for the hash and the lookup and saved nothing. On top of that the table itself lives until the end of the process — an interned string is not freed even when it is no longer needed.
So CPython interns automatically only where the gain is almost guaranteed: short literals that look like identifiers, and attribute names. Exactly what falls under the rule 🔧 has changed between versions and cannot be relied on.
When to call sys.intern by hand. When many records with repeating string fields are loaded into memory — categories, country codes, column names. A measurement from this lesson: a million strings from a small vocabulary, 21.2 MB versus 2.6 MB. The sign of the situation is few unique values among a large number of them. If there are almost as many unique values as values in total, interning will only slow things down.
There was a choice between two evils, and both were bad.
Before 3.3 CPython was built in one of two modes: a “narrow” build with UTF-16 inside and a “wide” one with UCS-4. The narrow build saved memory on Latin text but broke the semantics: characters outside the basic plane took two positions, so len("𝄞") returned 2 and a slice could cut a character in half. The wide build was correct but spent 4 bytes on every letter “a”.
PEP 393 removed the choice: a string looks at its own highest code point and picks 1, 2 or 4 bytes per character. It is visible right in the header — the kind field — and the lab “What is in the bytes” shows it in a real dump.
import sys
print(sys.getsizeof("aaaaa"), sys.getsizeof("ааааа"))
# → 54 84 five Latin letters versus five Cyrillic ones
The price of the decision: a single emoji added to a string doubles or quadruples its memory as a whole, because the representation is chosen for the entire string at once. The gain: len and indexing stayed O(1) and always count characters, not bytes — something JavaScript and Java still do not have.
float remained the exception: it is IEEE 754, and an int → float → int round trip above 2⁵³ loses data silently. Division rounds down, not toward zero, for the sake of an invariant from which it follows that a % n is always non-negative for a positive n — which is why Python has no need for ((i % n) + n) % n. A string is immutable, so it picks its character width once at creation: indexing stays O(1) at the cost of memory on mixed-alphabet text. And the same immutability gives interning, which turns from a curiosity about is into an eightfold memory saving if applied deliberately.
Java kept machine integers and added BigInteger as a separate class. The result: int overflow happens silently and wraps around modulo, and moving to big numbers means rewriting the code with methods instead of operators. Two sets of rules that you must choose between in advance — exactly what Python avoided.
C truncates division toward zero because that is what the hardware does. Python chose rounding down because that is more useful to a human, and paid with a divergence from the habits of half of all programmers.
Rust and Go treat a string as a sequence of UTF-8 bytes: indexing is by byte, and a character is obtained by iteration. In Rust s[0] simply does not compile. Python chose code points and O(1) indexing — and paid with three internal representations and extra memory on mixed-alphabet text.
Identifiers from an external system went through JSON and the comparison stopped working. No exception, no warning.
threshold = float(config["min_id"]) # "9007199254740993"
rows = [r for r in rows if r["id"] > threshold]
Everything looks normal: we convert the value from the config to a number and compare. But id here is a snowflake or some other 64-bit identifier, and float represents integers exactly only up to 2⁵³. The string “9007199254740993” turns into 9007199254740992, and records at the border sometimes make it into the selection and sometimes do not.
print(int(float("9007199254740993")))
# → 9007199254740992
Review lets it through because float() is the commonly accepted way to “convert to a number”, and the tests use small identifiers where everything matches. It shows up in production and only on some of the records, which makes the bug especially unpleasant to investigate.
The cure follows from consequence 1: for integers use int(), not float(). Python has no reason to take an integer into floating point — arbitrary-precision arithmetic is free as far as correctness goes. The same rule works for money: store cents as integers, not dollars as fractions.
Parsing a big log or CSV: keys, statuses and column names repeat millions of times, and each time it is a new object.
Strings that come out of parsing are not interned — the parser assembles them from pieces, and automatic interning works only for literals in code. So three hundred thousand identical statuses sit in memory as three hundred thousand objects:
value = sys.intern(parsed_field) # one function
| 300,000 repeated strings | memory |
|---|---|
| as is | 21.2 MB |
through sys.intern | 2.6 MB |
A factor of eight, and the code changes by one function. It works because interning reduces all identical strings to one object — that same consequence 5, applied deliberately.
When to use it: values from a limited set that repeat many times — statuses, country codes, column names, dictionary keys. When not to: unique values such as texts or identifiers — the interning table will only grow and there will be no gain. And remember that interned strings live until the end of the process: it is a cache with no eviction.
Run the four snippets and check them against your prediction. Then:
0.1 + 0.2 == 0.3
from decimal import Decimal
Decimal("0.1") + Decimal("0.2") == Decimal("0.3")
# Why are the answers different, and at what price is the second one obtained?
s = "a" * 1000
sys.getsizeof(s)
sys.getsizeof(s + "😀")
# How much will it grow, and why exactly that much?
hash("x") == hash("x")
# run this in two different processes — will it match?
(-7) // 2, int(-7 / 2)
# Two ways of integer division give different results. Which is needed when?
The third question leads to a topic the lesson does not cover: string hash randomization is on by default, and it is a protection against collision attacks. The answer is in the lesson on the dictionary.
Lib/statistics.py, function _sum. You expect to see floating-point addition — and instead there is a conversion to Fraction, exact addition of rationals, and a conversion back at the end.
This is done so that statistics.mean does not accumulate rounding error: the sum of a million floats in a naive loop drifts the more, the wider the spread of magnitudes. The standard library decided that for statistics precision matters more than speed, and allowed itself exact arithmetic — because the language has no primitives, and a rational number is just as much a first-class object as an integer.
Notice the flip side as well: statistics.mean is noticeably slower than sum(xs)/len(xs), and that is a deliberate trade written down in the source. A good example of “slow” and “wrong” being different axes.
From L1 you know that an integer is an array of digits and a string picks its width. Here: the concrete layout and its price.
The integer. A variable-length object header (24 bytes) plus an array of 32-bit words, each of which uses 30 bits. Why 30 and not 32: it leaves headroom for the carry in addition and multiplication, so that intermediate results do not exceed the machine word. Hence the size arithmetic: 28 bytes up to 2³⁰, 32 up to 2⁶⁰, then 4 bytes for every further 30 bits.
The cost of operations grows accordingly:
multiplying small integers 0.006 s
multiplying 5000-bit numbers 3.68 s (the same series of calls)
A difference of six hundred times — on the schoolbook multiplication algorithm, quadratic in the number of digits. For very large numbers CPython switches to Karatsuba, but the constant is still large.
The string. The header holds the length, the hash (computed lazily and cached), flags and the kind field — 1, 2 or 4 bytes per character. The compact ASCII form saves a few more fields, which is why an empty ASCII string is 49 bytes and not 74.
print(sys.getsizeof(""), sys.getsizeof("a")) # ASCII
# → 49 50
print(sys.getsizeof("é"), sys.getsizeof("😀")) # not ASCII
# → 74 80
The cached hash is an important detail in its own right: it is computed once, the first time the string is used as a key, and from then on taken from the header. That is why repeated lookups of the same string in a dictionary are cheaper than they seem — and also why interning saves not only memory but the hash computation too.
Tag v3.11.15.
Include/cpython/longintrepr.h — the definition of PyLongObject and the constant PyLong_SHIFT, equal to 30. Twenty lines that explain the whole of consequence 1.Objects/longobject.c, l_divmod — the implementation of division with rounding down and correction of the remainder. Consequence 3 as code.Include/cpython/unicodeobject.h — the three representations, the compact and ascii flags, the kind field.encode and decode — that is about the border with the outside world, not about the object model// and % — selectively: the paragraph on rounding down and the sign of the remainder. Half a page that closes consequence 3.