Python's int never overflows and a bool is an int, so sum(v >= 130 for v in sbp) counts the 1,900 of 5,247 NHANES 2017 to 2018 adults whose mean systolic reading is at least 130 mm Hg. A float is an IEEE 754 binary64 number: 0.1 is stored as $3602879701896397/2^{55}$, so 0.1 + 0.2 == 0.3 is False and round(2.675, 2) is 2.67. round breaks exact ties toward the even digit, keeping the total error of any run of halves within one half. NaN is unequal to itself, and bytes never equal strings. A set answers membership about 1,000 times faster than a list of the 5,533 respondent ids, at 524,504 bytes against 47,160. A mutable object bound to two names changes for both.
Of the 5,247 NHANES 2017 to 2018 adults with a systolic blood pressure reading, how many have a mean reading of at least 130 mm Hg? In plain Python the answer is one line, sum(v >= 130 for v in sbp), which returns 1,900. The line works because of three facts about Python's built-in types: a comparison produces a Boolean, a Boolean is an integer (True counts as 1), and sum adds integers. A different line, 0.1 + 0.2 == 0.3, returns False, because of a fourth fact, about how computers store fractions.
This article covers the built-in types that analysis code is built from: numbers, strings, the four containers (lists, tuples, sets and dictionaries), and the relation between names and the objects they refer to. It concentrates on the behavior that produces wrong answers rather than error messages. Programming with Python and Jupyter introduces names and objects; The NumPy Package and The pandas Package build arrays and tables on top of these types, and change some of their rules.
Every result here comes from tools/experiments/data-science/python-data-types.py in the site's repository, run with Python 3.13.5 on an Intel Core i9-9900K (rerun on 23 November 2026, when one check also ran a Python 3.11.0 interpreter on the same machine). The data are the 5,533 adults examined in NHANES 2017 to 2018, joined from the public files as in Performing Exploratory Data Analysis.
Numbers
Integers
Python's int has no fixed size. 2**100 is 1267650600228229401496703205376, exactly, and 100 factorial, a number with 158 digits, is computed without loss. An integer grows as needed: the object for 1 occupies 28 bytes and the object for $2^{100}$ 40 bytes. Integer arithmetic therefore never overflows, which is not true of the fixed-width integers of NumPy and pandas, where a calculation that exceeds the width wraps around silently (The NumPy Package shows a real case). Code that moves between the two can change its answer without warning.
Division has two operators. 7 / 2 is 3.5, a floating-point number, and 7 // 2 is 3, the floor of the quotient. The floor rounds toward minus infinity, not toward zero, so -7 // 2 is $-4$, and the remainder follows the same convention: -7 % 2 is 1. The two are tied together by the identity x == (x//y)*y + (x%y), which the language reference states (Python Software Foundation, 2025e): with the floor $-4$, the remainder must be $-7 - (-4)(2) = 1$.
Booleans
True and False are the two values of type bool, which is a subclass of int: isinstance(True, int) is True, and True + True is 2. This is what makes counting with comparisons work, as in the opening example, and what makes the mean of a list of Booleans a proportion: 1,900 of 5,247 is 36.2%.
Floating-point numbers
A float is a binary floating-point number in the IEEE 754 double-precision (binary64) format (IEEE, 2019): a sign, an 11-bit exponent and a 52-bit fraction, giving 53 significant bits (Python Software Foundation, 2025a). Within its normal range, from about $2.2 \times 10^{-308}$ to $1.8 \times 10^{308}$ (smaller "subnormal" values exist, with fewer significant bits), a float carries about 15 to 17 significant decimal digits. The consequences follow from one observation that Goldberg (1991) makes at the start of his classic survey: the decimal number 0.1 "has a finite decimal representation, in binary it has an infinite repeating representation", so it lies strictly between two floating-point numbers and is exactly representable by neither.
The float nearest to 0.1 is exactly
$$0.1000000000000000055511151231257827021181583404541015625 = \frac{3602879701896397}{2^{55}},$$
as decimal.Decimal(0.1) and fractions.Fraction(0.1) show, and as Worked problem 1 derives from the format: it is the nearest multiple of $2^{-56}$ to one tenth, larger by 0.4 of that spacing. Every literal 0.1 in a program means this number, and arithmetic on such numbers is rounded at each step to the nearest representable result. The IEEE standard "requires that the result of addition, subtraction, multiplication and division be exactly rounded", that is, computed exactly and then rounded to the nearest floating-point number (Goldberg, 1991), so each step is as accurate as the format allows. But the rounding errors of the inputs remain, and they show:
| Expression | Result |
|---|---|
0.1 + 0.2 |
0.30000000000000004 |
0.1 + 0.2 == 0.3 |
False |
math.isclose(0.1 + 0.2, 0.3) |
True |
round(2.675, 2) |
2.67 |
1e16 + 1 - 1e16 |
0.0 |
float(2**53 + 1) == float(2**53) |
True |
The documentation of round uses this very example (Python Software Foundation, 2025d): round(2.675, 2) gives 2.67 rather than 2.68 because the stored value of 2.675 is 2.67499999999999982236431605997495353221893310546875, slightly below the halfway point. 1e16 + 1 cannot be represented: the spacing between floats near $10^{16}$ is 2, so the exact sum lies half-way between $10^{16}$ and $10^{16} + 2$, the tie is resolved toward the neighbor with an even significand, $10^{16}$, and the 1 is lost entirely (Worked problem 2). Integers above $2^{53}$ are no longer all representable, because a 53-bit significand times a power of two of at least 2 can only be even. The relative spacing of floats near 1, the machine epsilon, is $2^{-52} \approx 2.22 \times 10^{-16}$ (sys.float_info.epsilon).
Three habits follow. Compare floats with a tolerance, math.isclose(a, b) or numpy.isclose, never with == unless both sides were computed the same way. Do not use floats for quantities that must be exact in decimal, such as currency, where Python's decimal module or integer cents are appropriate. And be wary of subtracting nearly equal numbers that both carry rounding error, which Goldberg (1991) calls catastrophic cancellation: the leading digits cancel and what remains is mostly error. The NumPy Package shows it in a variance computed by the shortcut formula $\overline{x^2} - \bar{x}^2$ in single precision.
Summation deserves a note because it is the commonest operation in statistics. Adding 0.1 ten times in a loop gives 0.9999999999999999. The built-in sum gave the same through Python 3.11; from Python 3.12 it "uses Neumaier summation to improve accuracy and commutativity" (Python Software Foundation, 2023; the sum entry of Python Software Foundation, 2025d, records the change in version 3.12), and sum([0.1] * 10) returns 1.0, as the script shows under Python 3.13.5; the same call under Python 3.11.0, run by the script on the same machine, returns 0.9999999999999999. math.fsum, which tracks the rounding error of every addition, returns 1.0 in both versions. Worked problem 4 shows that 1.0 is the correctly rounded answer. The same program can therefore print different final digits under different Python versions, a reason to state versions alongside results. It is also why this site's experiment scripts, in their review blocks, compute any number that decides a result or a printed digit in exact rational arithmetic (fractions.Fraction) and round it half up from the exact value, instead of relying on the built-in sum over floats.
Python's round uses round half to even, rounding a value exactly halfway between two candidates "toward the even choice" (Python Software Foundation, 2025d): round(0.5) is 0, round(1.5) is 2 and round(2.5) is 2. Rounding halves to the even neighbor avoids the upward bias that always rounding halves up introduces into sums of rounded values; Worked problem 3 proves this for a run of consecutive halves and separates the tie rule from the representation error that makes round(2.675, 2) give 2.67.
NaN
IEEE 754 also defines special values: infinities and NaN ("not a number"), the result of undefined operations such as $0/0$ in floating point. pandas and NumPy use NaN as the marker for a missing measurement, which is why it matters here. NaN is not equal to anything, including itself: nan == nan is False, and the test for it is math.isnan(x) (or pd.isna). One surprise follows from Python's containers, which check identity before equality (for a list, the language reference defines x in y as any(x is e or x == e for e in y); Python Software Foundation, 2025e): with nan = float("nan"), the expression nan in [nan] is True because it is the same object, while float("nan") in [nan] is False. Code that tests for missing values with == or in is wrong; Cleaning Data treats missing values in tables properly.
Strings and bytes
A str is an immutable sequence of Unicode characters. len("café") is 4 characters, although its UTF-8 encoding takes 5 bytes. Strings cannot be changed in place, word[0] = "N" raises TypeError: 'str' object does not support item assignment, so every string method returns a new string.
Text and numbers do not mix: "120" + 1 raises TypeError, and "120" + "1" is the string "1201", a common bug when numbers are read from a file as text. int("120") + 1 is 121.
f-strings are the standard way to put values into text. A format specification after a colon controls the output:
| Expression | Output |
|---|---|
f"{m:.1f}" |
126.4 |
f"{n:,}" |
5,533 |
f"{p:.1%}" |
36.2% |
f"{m=:.2f}" |
m=126.36 |
where m is the mean systolic pressure of the 5,247 adults, n the number of adults and p the share at or above 130. The last form, with =, prints the expression as well as its value, which is useful for checking intermediate results.
Python 3 separates text from bytes, sequences of 8-bit values with no character encoding attached. Data files are bytes until decoded, and some readers return them undecoded. The NHANES prescription file, read with pandas.read_sas (under pandas 2.2.3 and 3.1.1 alike, checked on 23 November 2026), gives each generic drug name as bytes, with an empty b'' where none was recorded: the first non-empty name is b'ENALAPRIL; HYDROCHLOROTHIAZIDE'. A bytes value never equals a string, b'MELOXICAM' == 'MELOXICAM' is False, so a filter for a drug name written as a string silently matches nothing until the column is decoded, as this site's data loader does with value.decode("latin-1").
Containers
Python has four general-purpose built-in containers. They differ in whether their elements keep an order, whether they can be changed after creation, and how elements are found:
| Type | Example | Ordered | Mutable | Elements found by | Duplicates |
|---|---|---|---|---|---|
| list | [120, 135] |
yes | yes | position | allowed |
| tuple | (1, "female") |
yes | no | position | allowed |
| set | {1, 2, 3} |
no | yes | value (hash) | removed |
| dict | {"never": 3301} |
insertion order | yes | key (hash) | keys unique |
A list is the general sequence. A tuple is a fixed record, such as a pair of coordinates or the several values a function returns (Python Functions). A set holds distinct values; the race codes of the NHANES adults, {int(r) for r in adults.race}, are the six codes 1, 2, 3, 4, 6 and 7. A dict maps keys to values; since Python 3.7, iteration over a dictionary follows the order in which keys were inserted, a guarantee of the language rather than an implementation detail (Python Software Foundation, 2025b).
Costs
Lists and tuples store their elements in a contiguous array of references, so access by position is immediate, while finding a value means comparing against the elements one by one. Sets and dictionaries are hash tables: an element's hash value tells Python where to look, so membership tests and lookups take, on average, about the same time however large the collection is. The difference is large even for small data. Searching the list of the 5,533 respondent numbers for a number that is not there takes tens of microseconds on this machine; searching a set of the same numbers takes tens of nanoseconds, about 1,000 times less (962 and 1,131 times in two runs of the script, and 1,112 in a rerun on 23 November 2026). A loop that checks membership in a list inside another loop over the same data is quadratic, and turning the list into a set once is often the whole fix.
The speed costs memory. The list of 5,533 numbers takes 47,160 bytes for its array of references and the tuple 44,304. The list was built by a comprehension, so it grew as elements were appended, and sys.getsizeof counts its spare slots too: 5,888 slots in all, the same size the comprehension lists of 5,247 and 5,232 elements below and in The NumPy Package reach. A list of the same 5,533 numbers made at once by tolist() takes 44,320 bytes. The set takes 524,504 bytes and a dictionary of the same keys 294,992, before counting the 28-byte integer objects that all of them refer to. These are the sizes of the containers themselves, from sys.getsizeof in 64-bit CPython 3.13; they are details of the implementation, and other versions can give different figures (as they can for the 28-byte integer and the generator object below).
Hashability
Sets and dictionary keys must be hashable: an object is hashable "if it has a hash value which never changes during its lifetime" (Python Software Foundation, 2025c). Immutable built-in values are hashable, mutable containers are not. {[1, 2]: "x"} raises TypeError: unhashable type: 'list', and so does a tuple that contains a list, hash((1, [2])), because a tuple is hashable only if everything in it is. "Keys must be immutable" is the usual short form of the rule; "keys must be hashable" is the precise one.
Assignment to a key creates the key if it does not exist, so a misspelt key adds an entry instead of raising an error: after d["curent"] = 1, the dictionary {"never": 0, "former": 0} has three keys. Reading a missing key does raise KeyError, and d.get(key, default) reads with a fallback.
Names, objects and aliasing
Programming with Python and Jupyter describes assignment as binding a name to an object. With immutable objects such as numbers, strings and tuples, the distinction between the name and the object rarely matters, because the object cannot change. With mutable objects it decides what a program does.
Several common mistakes are this one picture in different forms.
Repeated inner lists. The expression [ [0] * 3 ] * 3, meant to build a 3 by 3 grid of zeros, makes a list containing the same inner list three times. Setting grid[0][0] = 1 changes all three rows, giving rows [1, 0, 0], [1, 0, 0] and [1, 0, 0]. A comprehension, [ [0] * 3 for _ in range(3) ], makes three separate lists.
Shallow copies. copy.copy(record) makes a new dictionary whose values are the same objects as the original's. For a record {"seqn": 1, "readings": [130, 128]}, appending a reading to the original's list also changes the shallow copy's, since it is the same list; copy.deepcopy copies the nested list too and is unaffected.
Immutable is not frozen. A tuple cannot be changed, but the objects it holds can: appending to the list inside (1, [130, 128]) gives (1, [130, 128, 200]).
Augmented assignment. For a list, x += [3] changes the list in place, so another name y bound to the same list sees [1, 2, 3]. For a tuple, which cannot change, u += (3,) creates a new tuple and rebinds u, leaving v as (1, 2). The same operator mutates or rebinds depending on the type.
The test for "same object" is is, and for "equal value" is ==. is is reserved for identity questions, chiefly x is None. The same aliasing question arises for arrays and tables, where it is called views and copies; NumPy and pandas answer it differently, and pandas changed its answer in version 3 (The pandas Package).
Comprehensions
A comprehension builds a container from an iterable in one expression, optionally filtering:
high = [round(v) for v in sbp if v >= 180] # list: 95 adults
races = {int(r) for r in adults.race} # set: {1, 2, 3, 4, 6, 7}
counts = {s: smk.count(s) for s in set(smk)} # dict
A comprehension says what the result is rather than how to build it step by step. For counting, collections.Counter(smk) gives the smoking categories of the 5,533 adults directly, 3,301 never, 1,260 former and 972 current smokers, and the same dictionary as the explicit loop d[s] = d.get(s, 0) + 1.
Parentheses instead of brackets make a generator expression, which produces its values one at a time instead of storing them. sum(v >= 130 for v in sbp) from the opening example is one: the generator object occupies 200 bytes however long the data, while the list [v >= 130 for v in sbp] occupies 47,160 bytes for its references. For a single pass over large data, the generator avoids building a list that is used once.
For numerical work on many values, neither lists nor comprehensions are the right tool. NumPy arrays hold numbers in a fixed-width binary form, compactly and with arithmetic that runs in compiled loops, which is the subject of The NumPy Package.
Worked problems
The four problems derive the floating-point facts that the body states from the binary64 format itself. Each uses only the format (a sign, a 53-bit significand $m$ with $2^{52} \le m < 2^{53}$ for normal numbers, and a power of two) and the rule that every result is the representable number nearest the exact one, with ties going to the even significand (Goldberg, 1991). The script's review block checks every step in exact rational arithmetic.
Problem 1 (the stored value of 0.1). Derive $3602879701896397 / 2^{55}$ without asking Python.
Solution. Since $2^{-4} = 0.0625 \le 0.1 < 0.125 = 2^{-3}$, a float near 0.1 has the form $m \times 2^{-4} \times 2^{-52} = m / 2^{56}$ with $2^{52} \le m < 2^{53}$. Consecutive floats there are $2^{-56}$ apart. The nearest one to $1/10$ has $m$ equal to the integer nearest $2^{56}/10 = 7{,}205{,}759{,}403{,}792{,}793.6$, which is $m = 7{,}205{,}759{,}403{,}792{,}794$; the fractional part 0.6 is not a tie, so no tie rule is needed. Then $m / 2^{56} = 3{,}602{,}879{,}701{,}896{,}397 / 2^{55}$ after cancelling a factor of 2, the value Fraction(0.1) reports. Rounding moved the number up by $0.4 \times 2^{-56}$, about $5.55 \times 10^{-18}$, which is why the decimal expansion in the body begins 0.1000000000000000055. The same computation for 2.675, which lies in $[2, 4)$ where the spacing is $2^{-51}$, gives $2.675 \times 2^{51}$ with fractional part 0.4, so it rounds down. The stored value is below 2.675 by about $1.78 \times 10^{-16}$, the fact behind round(2.675, 2).
Problem 2 (why 1e16 + 1 - 1e16 is 0). Show that the 1 is lost, and predict 1e16 + 3.
Solution. Since $2^{53} \approx 9.007 \times 10^{15} \le 10^{16} < 2^{54}$, floats in this range are $m \times 2^{53-52} = 2m$, so the spacing is 2 (math.ulp(1e16) is 2.0). The exact sum $10^{16} + 1$ lies exactly half-way between $10^{16} = 2 \times (5 \times 10^{15})$ and $10^{16} + 2 = 2 \times (5 \times 10^{15} + 1)$. The tie goes to the even significand, $5 \times 10^{15}$, so the sum rounds to $10^{16}$, and subtracting $10^{16}$ leaves 0. By the same rule $10^{16} + 3$ is half-way between significands $5 \times 10^{15} + 1$ (odd) and $5 \times 10^{15} + 2$ (even), so it rounds up to $10^{16} + 4$. Adding a small number to a large one can therefore lose it or round it up to twice its size, depending only on the last bit of the large one.
Problem 3 (round half to even against half up). For a run of $L$ consecutive halves, find the total rounding error of each rule, and show that half to even keeps it bounded while half up lets it grow with $L$. Then explain why round(0.125, 2) and round(2.675, 2) both end in a smaller digit than a person rounding by hand expects, and show that the two causes differ.
Solution. Claim. For the halves $k + \tfrac{1}{2}$, $k = a, a + 1, \ldots, a + L - 1$ (any integer $a$, any length $L \ge 1$), rounding half up has total error exactly $L/2$. Rounding half to even has total error 0 when $L$ is even and $\pm\tfrac{1}{2}$ when $L$ is odd: $-\tfrac{1}{2}$ if $a$ is even, $+\tfrac{1}{2}$ if $a$ is odd.
Proof. Half up rounds every $k + \tfrac{1}{2}$ to $k + 1$, an error of $+\tfrac{1}{2}$ each, so the $L$ errors total $L/2$. Half to even rounds $k + \tfrac{1}{2}$ to whichever of $k$ and $k + 1$ is even: down, with error $-\tfrac{1}{2}$, when $k$ is even, and up, with error $+\tfrac{1}{2}$, when $k$ is odd. Split the run into consecutive pairs $(a, a + 1), (a + 2, a + 3), \ldots$. Each pair holds one even and one odd $k$, so its two errors cancel. If $L$ is even the pairs use up the run and the total is 0. If $L$ is odd one term is left over, the last one, $k = a + L - 1$, which has the parity of $a$ because $L - 1$ is even; its error, $-\tfrac{1}{2}$ for even $a$ and $+\tfrac{1}{2}$ for odd $a$, is the total. $\square$
So half to even is not exactly unbiased on every run, but its total error never exceeds half a unit, while half up's grows linearly with the number of ties. Example. For $k = 0, \ldots, 99$ ($a = 0$, $L = 100$) the exact total is $\sum_{k=0}^{99} k + 50 = 4{,}950 + 50 = 5{,}000$; half up gives $5{,}050$ and half to even $5{,}000$. For $k = 0, 1, 2$ the half-to-even errors are $-\tfrac{1}{2}, +\tfrac{1}{2}, -\tfrac{1}{2}$, total $-\tfrac{1}{2}$, as the claim says for odd $L$ and even $a$. The script confirms both cases and checks the claim for every start from 0 to 9 and every length from 1 to 40. For ties scattered over data rather than in a run, the same pairing argument applies to the even and odd neighbors that occur, so the bias is small when the two occur about equally often.
Now the two calls. 0.125 is $1/8$, exactly representable, so round(0.125, 2) faces a true tie between 0.12 and 0.13 and goes to the even last digit, 0.12; rounding the exact value half up would give 0.13. Here the cause is the tie rule. 2.675 is not representable: by Problem 1 the stored value is below 2.675, so there is no tie at all, and both rules give 2.67 from the stored value; only the decimal 2.675, which the program never holds, rounds half up to 2.68. Here the cause is representation, and no choice of tie rule changes it. This site's scripts avoid both effects by rounding exact rational values half up.
Problem 4 (sum([0.1] * 10) by version). What is the correctly rounded sum of ten copies of the stored 0.1, and how far from it are the loop and the two versions of sum?
Solution. Exactly, $10 \times 3{,}602{,}879{,}701{,}896{,}397 / 2^{55} = 36{,}028{,}797{,}018{,}963{,}970 / 2^{55} = 1 + 2^{-54}$, since $2^{55} = 36{,}028{,}797{,}018{,}963{,}968$. Above 1 the floats are $2^{-52}$ apart, so $1 + 2^{-54}$ is a quarter of a spacing above 1.0 and rounds to 1.0. That is the correctly rounded answer, and math.fsum, which tracks partial sums to avoid loss of precision (Python Software Foundation, 2025f), returns it. The loop instead rounds after each of its ten additions, and the errors accumulate downward: it ends at $1 - 2^{-53}$, printed 0.9999999999999999, the float just below 1. Python 3.11.0's sum gives the same value as the loop, as the script checks. Python 3.13.5's sum carries a compensation term that collects the rounding error of each addition (Neumaier's method) and adds it back at the end, which here recovers the correctly rounded 1.0. The difference between versions is therefore one unit in the last place, and the newer version is the correct one.
Open questions
- How often does Python 3.12's compensated
sumchange a published digit? Rerunning this collection's scripts under Python 3.11 and 3.13 and comparing every printed number would measure how many results depend on the summation algorithm, and whether any crosses a rounding boundary. - Does rounding half to even remove bias on real measurements? NHANES records blood pressures as even whole numbers and means of up to three readings; tabulating how often their means at one decimal end in an exact half, and the total error of each tie rule, would show whether the proof's equal split of even and odd neighbors holds for such data. Types of Numerical Data shows that all 15,146 systolic readings of the 5,247 adults are even, so ties at one decimal arise only from the averaging.
- When does a set stop paying for its memory? The list against set comparison here used 5,533 ids. Timing membership against the number of lookups and the size of the collection, including the cost of building the set, would locate the break-even point for one-off checks.
Where it leads
This article established the rules of Python's built-in values: unlimited integers, rounded floats, NaN, text against bytes, the four containers and their costs, and names bound to shared objects. Python Functions builds on the last of these, since passing an argument binds a name in the same way, and The NumPy Package replaces the containers with fixed-width arrays whose integers, unlike Python's, can overflow.
References
- Goldberg, D. (1991). What every computer scientist should know about floating-point arithmetic. ACM Computing Surveys, 23(1), 5–48. https://doi.org/10.1145/103162.103163 record · 2 pages
- IEEE (2019). IEEE Standard for Floating-Point Arithmetic (IEEE Std 754-2019). https://doi.org/10.1109/IEEESTD.2019.8766229 record
- Python Software Foundation (2023). What's New In Python 3.12. Python 3 documentation. https://docs.python.org/3/whatsnew/3.12.html record · 2 pages
- Python Software Foundation (2025a). Floating-Point Arithmetic: Issues and Limitations. The Python Tutorial. https://docs.python.org/3/tutorial/floatingpoint.html record
- Python Software Foundation (2025b). Built-in Types (section "Mapping Types: dict"). Python 3 documentation. https://docs.python.org/3/library/stdtypes.html record
- Python Software Foundation (2025c). Glossary (entry "hashable"). Python 3 documentation. https://docs.python.org/3/glossary.html record · 2 pages
- Python Software Foundation (2025d). Built-in Functions (entries "round" and "sum"). Python 3 documentation. https://docs.python.org/3/library/functions.html record
- Python Software Foundation (2025e). The Python Language Reference, section 6, "Expressions" (binary arithmetic operations; membership test operations). https://docs.python.org/3/reference/expressions.html record · 3 pages
- Python Software Foundation (2025f). math: Mathematical functions (entry "fsum"). Python 3 documentation. https://docs.python.org/3/library/math.html record
Reviewed: verified, 23 Nov 2026 · citations checked, 23 Nov 2026 · editorial review, 23 Nov 2026 · 5 revisions