Course contents 02 / 22

02 / 22 · Getting Started

Values, types and names

Python's model of data: every value is an object with an identity, a type and a value, a name refers to an object, and assignment copies nothing; is against ==, mutability, int, float, bool and None, and dynamic but strong typing.

Prerequisites

Running Python

On this page 10

The previous note ran programs made of two kinds of step: creating a value, such as 3 or [12, 15, 9], and giving it a name, such as width. This note asks what those two things are. The answer is short and it carries the rest of the course: every value in Python is an object that lives somewhere in memory, a name is a reference to an object, and = attaches a name to an object without copying anything. Most of the surprises that newcomers meet, a list that changes “by itself”, a default argument that remembers, a copy that is not a copy, follow from this one rule. The note then goes through the four simplest types, int, float, bool and None, and ends with what it means that Python is dynamically but strongly typed.

Baseline: a variable as a box#

A common first picture of a variable, from school algebra or from languages such as C, is a box with a label. x = 3 puts 3 into the box x; y = x copies the 3 into a second box y; changing y leaves x alone. For numbers in Python the picture gives the right answers. For a list it does not:

>>> a = [1, 2]
>>> b = a
>>> b.append(3)
>>> a
[1, 2, 3]

b.append(3) adds 3 to the end of the list named b, and the list named a changed too. If b = a had copied a into a new box, a would still be [1, 2]. The box picture is wrong, and the right one has to explain both this session and why x and y seemed to behave like boxes.

Every value is an object#

The rule. Every value in Python, a number, a string, a list, a function, even None, is an object, and every object has three properties (Python language reference, §3.1):

  1. an identity, which never changes while the object exists; id(obj) returns it as an integer, and in CPython it is the object’s address in memory;
  2. a type, which says what operations the object supports; type(obj) returns it;
  3. a value, its contents. Whether the value can change depends on the type.
>>> x = 1000
>>> type(x)
<class 'int'>
>>> type([1, 2]), type("hi"), type(None), type(print)
(<class 'list'>, <class 'str'>, <class 'NoneType'>, <class 'builtin_function_or_method'>)

The identity is what makes an object a thing rather than a number written on paper. Two lists can hold the same values and still be two different objects, with two identities, in two places in memory.

Names are references, and assignment copies nothing#

The figure replays five statements:

Figure

Names refer to objects

The names a, b, c and three listsOn the left, five lines of code with step numbers. On the right, the names a, b and c with arrows to list objects. a and b first point to one list [1, 2, 3]; c points to a different list [1, 2, 3]; at the end b points to a new list [1, 2, 3, 4], and the old arrow from b is crossed out.codenamesobjects1a = [1, 2]2b = a3b.append(3)4c = [1, 2, 3]5b = b + [4]abc123list #11234list #3123list #2a sees the change: a is b → Truea == c → True, but a is c → Falsea is b → False; a is still [1, 2, 3]The names a, b, c and three listsOn the left, five lines of code with step numbers. On the right, the names a, b and c with arrows to list objects. a and b first point to one list [1, 2, 3]; c points to a different list [1, 2, 3]; at the end b points to a new list [1, 2, 3, 4], and the old arrow from b is crossed out.names → objects1a = [1, 2]2b = a3b.append(3)4c = [1, 2, 3]5b = b + [4]abc123list #11234list #3123list #2a sees the change: a is b → Truea == c → True, but a is c → Falsea is b → False; a is still [1, 2, 3]
Five statements, step by step. A name is a reference to an object; assignment binds a name to an object and copies nothing. After step 2, a and b refer to the same list #1, so a change made through b (3) is seen through a. Step 4 creates a separate list #2 with an equal value: == compares values, is compares identity. Step 5 builds a new list #3 and rebinds b (the cross marks the old reference), while a still refers to #1. The cells of a list hold references too; the lists note draws them.
  1. a = [1, 2] creates a list object and binds the name a to it.
  2. b = a evaluates a, which gives that same list object, and binds b to it. Nothing is copied: one list, two names.
  3. b.append(3) asks the object that b refers to to change. It is the only list there is, so a sees [1, 2, 3] too.
  4. c = [1, 2, 3] evaluates a new list display, which creates a new list. a and c are equal in value and are two objects.
  5. b = b + [4] evaluates b + [4]. For lists, + builds a new list from the two operands; then b is bound to it. The old list is untouched, and a still refers to it.

The REPL confirms each step:

>>> a = [1, 2]
>>> b = a
>>> b.append(3)
>>> a, a is b
([1, 2, 3], True)
>>> c = [1, 2, 3]
>>> a == c, a is c
(True, False)
>>> b = b + [4]
>>> a, b, a is b
([1, 2, 3], [1, 2, 3, 4], False)

Why it works this way. In CPython a name in a namespace is an entry that holds a pointer, eight bytes on a 64-bit machine, whatever the object. Binding a name writes a pointer, which costs the same for an integer and for a list of a million elements. Copying would have to know how deep to copy and would make every assignment cost time proportional to the size of the data. Python makes the cheap operation the default and asks you to request a copy explicitly: list(a), a.copy() or a[:] for a shallow copy of a list, copy.deepcopy(a) for a copy of everything inside it. The lists note shows what shallow means.

The same rule holds wherever a name is bound, not only at =: a for loop binds its loop variable to each item in turn, import math binds the name math to a module object, and calling a function binds its parameter names to the argument objects. The last one is why a function can change a list it was given, which the functions note takes up.

is against ==#

The rule. a is b is true when a and b refer to the same object, that is, when id(a) == id(b). a == b is true when the values are equal, as defined by the type: two lists are equal when they have equal elements in the same order. is cannot be redefined by a type; == is a method of the type and can be.

Use == to compare values and is only to ask “is this that very object?”. The one everyday use of is is the test for None, x is None, because there is exactly one None object.

The mistake. is on numbers or strings sometimes seems to work, because CPython reuses some objects:

>>> a = 256
>>> b = 255 + 1
>>> a is b
True
>>> c = 257
>>> d = int("257")
>>> c is d
False
>>> c == d
True

CPython keeps one object for each integer from −5 to 256 and returns it whenever such a number is created; 257 is created afresh each time (Python C API, integer objects). This is an optimization of one implementation, not a rule of the language, and code that relies on it breaks on the next number. The compiler warns when is is used with a literal:

>>> x = 1000
>>> x is 1000
<python-input-1>:1: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
False

Mutable and immutable objects#

The rule. An object whose value can change after it is created is mutable; one whose value cannot is immutable. Lists, dictionaries and sets are mutable. Numbers, strings, tuples, bool and None are immutable. For an immutable object no operation changes it; an operation that seems to change it creates a new object and rebinds the name.

That explains why the box picture worked for numbers. After y = x, both names refer to one int object, as for the list. But no operation can change that object, so the sharing can never be observed; x = x + 1 creates a new object 1001 and rebinds x, leaving y on 1000:

>>> x = 1000
>>> y = x
>>> y is x
True
>>> x = x + 1
>>> x, y
(1001, 1000)
>>> y is x
False

Augmented assignment differs by type. n += 1 on an int creates a new object and rebinds n. nums += [3] on a list extends the same list in place and then rebinds nums to that same object:

>>> nums = [1, 2]
>>> before = id(nums)
>>> nums += [3]
>>> id(nums) == before
True
>>> n = 10
>>> before = id(n)
>>> n += 1
>>> id(n) == before
False

The protocol behind this: x += y first tries the method __iadd__ of x’s type, an in-place addition, and falls back to x = x + y when the type has none. A list has __iadd__, an int does not (Python language reference, §7.2.1). So b += [4] in step 5 of the figure would have changed the list that a also refers to, where b = b + [4] did not. The data model note shows how a class of your own takes part in such protocols.

Immutable does not mean frozen all the way down. A tuple cannot change which objects it holds, but if one of them is a list, that list can change:

>>> t = ([1, 2], "x")
>>> t[0].append(3)
>>> t
([1, 2, 3], 'x')
>>> t[0] = [9]
Traceback (most recent call last):
  ...
TypeError: 'tuple' object does not support item assignment

Aliasing surprises#

Two names for one mutable object are called aliases. Aliasing is useful, since passing a large list to a function costs nothing, but it causes three classic bugs. Each has the same diagnosis: one object where you expected several. id() or is confirms it.

  • A changed argument. A function that appends to a list it was given changes the caller’s list, because the parameter is one more name for the same object.

  • A repeated inner list. [[0] * 3] * 2 builds one inner list and a two-element list whose elements are two references to it:

    >>> grid = [[0] * 3] * 2
    >>> grid[0][0] = 1
    >>> grid, grid[0] is grid[1]
    ([[1, 0, 0], [1, 0, 0]], True)
    >>> grid = [[0] * 3 for _ in range(2)]
    >>> grid[0][0] = 1
    >>> grid
    [[1, 0, 0], [0, 0, 0]]

    The second version evaluates [0] * 3 once per row and so builds two inner lists; the for inside square brackets is a list comprehension, the subject of the iteration note.

  • A remembered default. A function whose default argument is a list shares that one list across all calls. The functions note explains why.

The machine-learning courses meet aliasing at a larger scale. Slicing a NumPy array gives a view that shares memory with the original, so writing into the slice writes into the array (NumPy arrays), and PyTorch’s in-place operations change a tensor that other names, or the gradient computation, still refer to (PyTorch and automatic differentiation).

Numbers: int, float, bool#

int: integers without a size limit#

A Python int is an exact integer of any size. There is no overflow:

>>> 2 ** 100
1267650600228229401496703205376
>>> len(str(2 ** 10000))
3011

Why there is no limit. A C int is a fixed number of bits, 32 or 64, and arithmetic wraps around when the result does not fit (Bits, integers and byte order). CPython stores an int as a header followed by an array of digits in base 2302^{30}, each kept in a 4-byte C integer, and allocates as many digits as the number needs. sys.int_info reports the layout:

>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4, default_max_str_digits=4300, str_digits_check_threshold=640)
>>> [sys.getsizeof(2**k) for k in (0, 29, 30, 59, 60, 89, 90)]
[28, 28, 32, 32, 36, 36, 40]

The header takes 24 bytes on a 64-bit build (a reference count, a pointer to the type, and a field that stores the sign and the number of digits), and every number has at least one digit, so the smallest int takes 28 bytes. A number of bb bits needs ⌈b/30⌉\lceil b/30 \rceil digits:

size(b)=24+4 max⁡ ⁣(1,⌈b/30⌉) bytes.\text{size}(b) = 24 + 4\,\max\!\big(1, \lceil b / 30 \rceil\big) \text{ bytes}.

For 2302^{30}, which has 31 bits, that is 24+4⋅2=3224 + 4 \cdot 2 = 32, as measured.

Figure

The size of an int grows with its number of bits

Size of an int in bytes against its number of bitsA staircase: 28 bytes up to 30 bits, then 32, 36 and so on up to 64 bytes at 300 bits. The measured points lie on the steps.28405264060120180240300bits in the numberbytesa 24-byte header + 4-byte digits+4 bytes for every 30 bitsSize of an int in bytes against its number of bitsA staircase: 28 bytes up to 30 bits, then 32, 36 and so on up to 64 bytes at 300 bits. The measured points lie on the steps.284052640100200300bits in the numberbytesa 24-byte header + 4-byte digits+4 bytes for every 30 bits
sys.getsizeof(2**k) on CPython 3.14.7, 64-bit macOS (arm64), against the number of bits in 2**k, which is k + 1. A Python int is a 24-byte header and an array of 30-bit "digits" stored in 4 bytes each, so the size grows by 4 bytes every 30 bits. There is no upper limit: a number grows as long as memory lasts. The dots are measured values, the line is the formula 24 + 4·⌈bits/30⌉.

The price of exactness is speed: every operation on an int goes through a loop over its digits and allocates a new object for the result, where a C addition is one instruction. For the numbers of everyday code (counters, indices, sizes) that is one digit and the loop is short. NumPy stores numbers as fixed-width machine integers, which is faster and can overflow; the NumPy note shows where that matters. One deliberate limit exists: converting an int of more than 4300 decimal digits to a string raises ValueError unless the limit is raised with sys.set_int_max_str_digits (since Python 3.11), because the conversion takes time quadratic in the number of digits and could be used to stall a server (Python documentation, integer string conversion length limitation).

Division. / always gives a float, // is floor division, which rounds toward minus infinity, and % gives the remainder that matches it, so that a == (a // b) * b + a % b always holds:

>>> 7 / 2, 7 // 2, -7 // 2, 7 % 3, -7 % 3
(3.5, 3, -4, 1, 2)

For -7 // 2 the exact quotient −3.5-3.5 rounds down to −4-4. For -7 % 3 the floor quotient is −3-3 (from −2.33…-2.33\ldots), and the remainder is −7−(−3)⋅3=2-7 - (-3) \cdot 3 = 2. The remainder therefore has the sign of the divisor, which makes i % n a valid index into a list of length n for any integer i. C rounds toward zero instead, and its % can be negative.

float: IEEE 754 double precision#

A float is a 64-bit IEEE 754 binary floating-point number, the double of C: 53 significant bits, which is about 15 to 17 significant decimal digits (Floating point). Most decimal fractions have no exact binary representation, so they are stored rounded:

>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.2 == 0.3
False
>>> (0.1).as_integer_ratio()
(3602879701896397, 36028797018963968)
>>> from decimal import Decimal
>>> Decimal(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')

The literal 0.1 becomes the nearest double, which is the fraction 3602879701896397/2553602879701896397 / 2^{55}, slightly more than one tenth; Decimal(0.1) prints that stored value exactly. 0.2 is rounded the same way, and the sum of the two rounded values rounds to a double one step above the double nearest to 0.3. The floating-point note does the arithmetic bit by bit. What Python adds is the printing: repr of a float shows the shortest decimal string that reads back as the same double, which is why 0.1 displays as 0.1 even though it is not one tenth.

The rule that follows. Never compare floats that come out of arithmetic with ==. Compare with a tolerance, math.isclose(a, b) (relative tolerance 10−910^{-9} by default), or with abs(a - b) <= tol for a tolerance that suits the problem. Other consequences of the same model:

>>> round(2.675, 2)
2.67
>>> 2.0 ** 53 + 1
9007199254740992.0
>>> 1e308 * 10
inf
>>> float("nan") == float("nan")
False

2.675 is stored as slightly less than 2.675, so it rounds down. Above 2532^{53} consecutive integers are no longer all representable, and 253+12^{53} + 1 rounds to 2532^{53}. Overflow gives infinity rather than an error, and NaN (“not a number”), the result of undefined operations such as inf - inf, is not equal even to itself. Training a network in 32-bit or 16-bit floats, as the deep-learning courses do, makes each of these effects larger (Narrow formats for machine learning).

bool: two integers with names#

True and False are the only two objects of type bool, which is a subclass of int: True behaves as 1 and False as 0 in arithmetic.

>>> True + True
2
>>> isinstance(True, int)
True
>>> sum([True, False, True, True])
3

The last line is a common idiom: the number of elements that pass a test is the sum of the tests. Comparisons such as x > 0 produce a bool, and the control flow note shows how if turns any object into one.

None: the absence of a value#

None is the single object of type NoneType. It means “no value here”: a function that ends without return returns None, and None is the usual default for an optional argument.

>>> result = print("hi")
hi
>>> result is None
True
>>> None == 0, None == ""
(False, False)

print writes its output and returns None; in the REPL a None result is not displayed, which is why print("hi") showed only hi in the previous note. Since there is one None, the test is x is None, not x == None.

Dynamic and strong typing#

Dynamic typing. A name has no type; the object it refers to does. The same name can refer to an int now and a str later, and nothing is checked before the program runs:

>>> x = 5
>>> type(x)
<class 'int'>
>>> x = "five"
>>> type(x)
<class 'str'>

Strong typing. Each operation checks the types of the objects it receives at the moment it runs, and Python does not silently convert between unrelated types. Adding a string to a number is an error, not "34" and not 7:

>>> "3" + 4
Traceback (most recent call last):
  ...
TypeError: can only concatenate str (not "int") to str
>>> int("3") + 4, "3" * 4, 1 + 2.5
(7, '3333', 3.5)

The conversion has to be written, int("3"). The exceptions are deliberate and few: numbers mix freely (1 + 2.5 converts the int to a float), and bool counts as int. "3" * 4 is not a conversion but a defined operation, repetition of a string. Many errors in Python code are therefore found only when the line runs, which is one reason for tests and, since a checker can read them before the program runs, for type hints.

What changed#

Box picture (the baseline)Python’s model
A variable isa box that holds a valuea name bound to an object
b = acopies the valuebinds a second name to the same object
Change through binvisible through avisible through a if the object is mutable
Equalityone notion== compares values, is compares identity
Type belongs tothe variablethe object; names have none
Integersfixed width, can overflowexact, any size, stored in 30-bit digits

Limitations#

  • id and the cached integers are CPython’s. Other implementations give identities differently and cache other objects; the rule that is compares identity holds everywhere, the particular results do not.
  • Sizes are for one build. sys.getsizeof values are those of a 64-bit CPython 3.14; they differ on 32-bit builds and in other versions, and they count only the object itself, not the objects it refers to.
  • Containers come later. Lists, tuples, dictionaries and sets are only used here to show sharing. Their structure, the shallow copy and what their operations cost are the subject of the Data Structures section.
  • Other numeric types. complex, decimal.Decimal (exact decimal arithmetic for money) and fractions.Fraction (exact rationals) exist in the standard library and are not covered.

What you should remember#

  • Every value is an object with an identity, a type and a value. A name is a reference to an object.
  • Assignment binds a name to an object and copies nothing. Copies are made only when you ask: list(a), a.copy(), copy.deepcopy(a).
  • == compares values; is compares identity. Use is for None and almost nothing else.
  • Mutable objects (lists, dicts, sets) can change and so can be changed through any alias. Immutable objects (numbers, strings, tuples) cannot; “changing” one rebinds the name to a new object.
  • int is exact and unbounded; float is an IEEE 754 double, so compare results with a tolerance; bool is a kind of int; None is one object.
  • Python checks types at run time (dynamic) and does not convert between unrelated types silently (strong).

Code#

The script checks each claim of the note in order: sharing and rebinding, with a short label for each object’s identity; immutable against mutable +=; the shared-row trap; the size and division rules of int; the rounding of float; bool and None; and strong typing. Run it with python -I values.py. Object identities differ from run to run, which is why the script prints its own labels instead of raw id values; the sizes are those of a 64-bit build.

"""Names, objects and the built-in scalar types, checked one claim at a time (Python 3.14)."""
import math
import sys

# 1. Assignment binds a name; it never copies. Track objects by identity.
labels = {}
def label(obj):
    """A short stable label for an object's identity: #1, #2, ... in order of first sight."""
    return labels.setdefault(id(obj), f"#{len(labels) + 1}")

a = [1, 2]
b = a                      # same object
b.append(3)                # mutation: visible through every name
c = [1, 2, 3]              # an equal but separate object
print("a", label(a), a, "| b", label(b), b, "| c", label(c), c)
print("a is b:", a is b, " a == c:", a == c, " a is c:", a is c)
b = b + [4]                # + builds a new list; the name b is rebound
print("after b = b + [4]: a", label(a), a, "| b", label(b), b)

# 2. Immutable objects cannot change, so "changing" an int rebinds the name
n = 1000
first = id(n)
n += 1
print("int += gives a new object:", id(n) != first)
nums = [1, 2]
first = id(nums)
nums += [3]
print("list += changes the same object:", id(nums) == first)

# 3. The shared-row trap: one inner list referenced twice
grid = [[0] * 3] * 2
grid[0][0] = 1
print("shared rows:", grid, grid[0] is grid[1])
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print("separate rows:", grid)

# 4. int has no fixed width: its size grows by one 30-bit digit at a time
print(sys.int_info.bits_per_digit, [sys.getsizeof(2 ** k) for k in (0, 30, 60, 300)])
print(2 ** 100, (2 ** 100).bit_length())
print(7 // 2, -7 // 2, 7 % 3, -7 % 3)        # floor division rounds toward minus infinity

# 5. float is an IEEE 754 double: 53 significant bits
print(0.1 + 0.2, 0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
print((0.1).as_integer_ratio(), 2.0 ** 53 + 1 == 2.0 ** 53)
print(sys.float_info.epsilon, float("nan") == float("nan"))

# 6. bool is a subclass of int; None is a single object
print(True + True, isinstance(True, int), None is None, type(None).__name__)

# 7. Strong typing: no silent conversion between str and int
try:
    "3" + 4
except TypeError as err:
    print("TypeError:", err)
print(int("3") + 4, "3" * 4, 1 + 2.5)

# Output with CPython 3.14.7 on 64-bit macOS (arm64); sizes are those of a 64-bit build:
# a #1 [1, 2, 3] | b #1 [1, 2, 3] | c #2 [1, 2, 3]
# a is b: True  a == c: True  a is c: False
# after b = b + [4]: a #1 [1, 2, 3] | b #3 [1, 2, 3, 4]
# int += gives a new object: True
# list += changes the same object: True
# shared rows: [[1, 0, 0], [1, 0, 0]] True
# separate rows: [[1, 0, 0], [0, 0, 0]]
# 30 [28, 32, 36, 68]
# 1267650600228229401496703205376 101
# 3 -4 1 2
# 0.30000000000000004 False True
# (3602879701896397, 36028797018963968) True
# 2.220446049250313e-16 False
# 2 True True NoneType
# TypeError: can only concatenate str (not "int") to str
# 7 3333 3.5

Next#

Every program so far ran its lines once each, from top to bottom. Real programs choose: they run a block only when a condition holds, repeat it for every item of a list, or stop early when they find what they were looking for. The next note covers if, the two loops and match, and shows how if decides whether an arbitrary object, such as an empty list, counts as true.

References#