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. 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, so that (a // b) * b + a % b == a always holds.
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 range, from about $2.2 \times 10^{-308}$ to $1.8 \times 10^{308}$, 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. 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 1 is lost entirely, and integers above $2^{53}$ are no longer all representable. 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 until Python 3.11; from Python 3.12 it "uses Neumaier summation to improve accuracy and commutativity" (Python Software Foundation, 2023), and sum([0.1] * 10) returns 1.0, as the script shows under Python 3.13 (Python Software Foundation, 2025d); the same call under Python 3.11 returns 0.9999999999999999. math.fsum, which tracks the rounding error of every addition, returns 1.0 in both versions. The same program can therefore print different final digits under different Python versions, a reason to state versions alongside results.
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.
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: 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, 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 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). 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, while 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.
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
- 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