Values, types and names
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.
A name is not a box
The topic Running Python ran a first script, samples.py. Its lines did two kinds of things: they created values, such as 32 and 4, and gave them names, such as batch_size and steps. The topic also left a loose end. The arguments in sys.argv arrive as text, '10' and not the number 10. This topic asks what a value and a name really are, and on the way it explains why '10' and 10 are different things.
The usual first picture comes from school algebra: a variable is a box with a label. x = 3 puts 3 into the box x. y = x copies the 3 into a second box y, and changing y leaves x alone. For numbers this picture gives the right answers. For a list it does not:
a = [1, 2]
b = a
b.append(3)
print(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 the list into a new box, a would still be [1, 2]. So the box picture is wrong. The right picture has to explain this output, and also why numbers seemed to behave like boxes.
Every value is an object
Start with the values. Every value in Python is an object: a number, a string, a list, a function, even None. Every object has three properties:
- an identity, which never changes while the object exists.
id(obj)returns it as an integer. In CPython it is the object's address in memory. - a type, which says what operations the object supports.
type(obj)returns it. - a value, its contents. Whether the value can change depends on the type.
Here are all three on a short list of losses:
losses = [0.9, 0.7]
print(type(losses), type(0.9), type(None), type(print))
print(id(losses))
other = [0.9, 0.7]
print(losses == other, id(losses) == id(other))<class 'list'> <class 'float'> <class 'NoneType'> <class 'builtin_function_or_method'>
4323401664
True FalseThe second line is a memory address. It changes from run to run and from machine to machine, so never rely on a particular number. The last line matters more. losses and other hold equal values and are still two objects, with two identities, in two places in memory. Identity is what makes an object a thing rather than a number written on paper.
Assignment copies nothing
Now the names.
Key idea. A name is not a box that holds a value. It is a reference to an object. The assignment name = expression first evaluates the expression to an object and then binds the name to that object. Nothing is copied, and the object the name referred to before is not changed. Several names can refer to one object, and a change made through any of them is visible through all of them.
The puzzle from the first block, two steps further:
a = [1, 2]
b = a
b.append(3)
print(a, a is b)
c = [1, 2, 3]
print(a == c, a is c)
b = b + [4]
print(a, b, a is b)[1, 2, 3] True
True False
[1, 2, 3] [1, 2, 3, 4] Falseb = a evaluates a, which gives the existing list, and binds b to it: one list, two names. append changes that one list, so a sees the change. c = [1, 2, 3] creates a new list, equal to a but a separate object. Finally, b + [4] builds a new list, and only then is b bound to it. The old list is untouched, and a still refers to it. The operator is asks whether two names refer to the same object; the next block looks at it closely.
Why does Python work this way? In CPython a name is an entry that holds a pointer, eight bytes on a 64-bit machine, whatever the object. Binding a name writes one pointer. It costs the same for an integer and for a list of a million losses. A copy would take time proportional to the data, and it would have to guess how deep to go. So the cheap operation is the default, and a copy is made only when you ask: list(a), a.copy() or a[:] for a list, copy.deepcopy(a) for everything inside it too. The topic Lists and tuples shows the difference between the two.
The same rule holds wherever a name is bound. import math binds the name math to a module object. The topics Control flow and Functions show two more places: a for loop binds its variable to each item in turn, and a call binds the parameter names to the arguments.
`is` against `==`
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, in the sense the type defines. Two lists are equal when they have equal elements in the same order. A type can redefine ==, but not is.
The rule follows. Use == to compare values. Use is only to ask "is this that very object?". Its one everyday use is the test x is None: there is exactly one None object, so the answer is always reliable.
The trap. On numbers is sometimes seems to work, because CPython reuses some objects:
a = 256
b = 255 + 1
print(a is b)
c = 257
d = int("257")
print(c is d, c == d)True
False TrueCPython keeps one object for each integer from −5 to 256 and hands it out whenever such a number appears. 257 is created afresh. 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 about is with a literal: x is 1000 prints SyntaxWarning: "is" with 'int' literal. Did you mean "=="?. And the result itself is unreliable. With x = 1000, the same comparison gave True in a script and False when typed line by line into the REPL.
Mutable objects and aliases
An object whose value can change after it is created is mutable. One whose value cannot is immutable. Lists, dicts and sets are mutable. Numbers, strings, tuples, bool and None are immutable. No operation changes an immutable object. An operation that seems to change one creates a new object and rebinds the name.
This is why the box picture worked for numbers. After y = x both names refer to one int, exactly as with the list. But nothing can change that int, so the sharing is never visible:
x = 1000
y = x
print(y is x)
x = x + 1
print(x, y, y is x)True
1001 1000 FalseAugmented assignment depends on the type. x += y first tries the method __iadd__ of the type of x, an in-place addition. If the type has none, it falls back to x = x + y. A list has __iadd__, an int does not:
nums = [1, 2]
alias = nums
nums += [3]
print(alias, alias is nums)
n = 10
before = id(n)
n += 1
print(id(n) == before)[1, 2, 3] True
FalseSo b += [4] in the previous example would have changed the list that a also sees, where b = b + [4] did not.
Two names for one mutable object are aliases. Aliasing is useful: passing a large list to a function costs nothing. But it causes classic bugs, all with one diagnosis: one object where you expected several. Here is the shortest:
grid = [[0] * 3] * 2
grid[0][0] = 1
print(grid, grid[0] is grid[1])
grid = [[0] * 3, [0] * 3]
grid[0][0] = 1
print(grid, grid[0] is grid[1])[[1, 0, 0], [1, 0, 0]] True
[[1, 0, 0], [0, 0, 0]] FalseThe first line evaluates [0] * 3 once, and * 2 repeats a reference to that one row. The fixed version evaluates [0] * 3 twice and gets two rows. A function that changes a list it was given, or a default argument that remembers, are the same bug; the topic Functions takes them up. The ML courses meet it at a larger scale: a slice of a NumPy array shares memory with the array, and an in-place PyTorch operation changes a tensor that other names still refer to.
int: exact integers of any size
Now the simplest types, starting with int. A Python int is an exact integer of any size. There is no overflow:
import sys
print(2 ** 100)
print(len(str(2 ** 10000)))
print(sys.int_info.bits_per_digit)
print([sys.getsizeof(2 ** k) for k in (0, 29, 30, 59, 60)])1267650600228229401496703205376
3011
30
[28, 28, 32, 32, 36]A C int is a fixed 32 or 64 bits, and its arithmetic wraps around when a result does not fit. CPython stores an int as a header followed by an array of digits in base , each kept in 4 bytes, and allocates as many digits as the number needs. On a 64-bit build the header takes 24 bytes, and every number has at least one digit. A number of bits therefore takes
For , which has 31 bits, that is , as measured. These sizes belong to 64-bit CPython 3.14; other builds differ. The price of exactness is speed: each operation loops over the digits and allocates a new object. NumPy uses fixed-width machine integers instead, which is faster and can overflow.
Division. / always gives a float. // is floor division: it rounds toward minus infinity. % gives the matching remainder, so that a == (a // b) * b + a % b always holds:
print(7 / 2, 7 // 2, -7 // 2, 7 % 3, -7 % 3)3.5 3 -4 1 2For -7 // 2 the exact quotient rounds down to . For -7 % 3 the floor quotient is , and the remainder is . The remainder takes the sign of the divisor, so i % n is a valid index into a list of length n for any integer i. C rounds toward zero instead, and its % can be negative.
float, bool and None
A float is a 64-bit IEEE 754 binary number, the double of C. It has 53 significant bits, about 15 to 17 decimal digits. Most decimal fractions have no exact binary form, so they are stored rounded:
import math
print(0.1 + 0.2, 0.1 + 0.2 == 0.3)
print((0.1).as_integer_ratio())
print(math.isclose(0.1 + 0.2, 0.3))
print(1e308 * 10, float("nan") == float("nan"))0.30000000000000004 False
(3602879701896397, 36028797018963968)
True
inf FalseThe literal 0.1 becomes the nearest double, the fraction , slightly more than one tenth. 0.2 is rounded the same way, and their sum lands one step above the double nearest to 0.3. Python prints the shortest decimal string that reads back as the same double, which is why 0.1 shows as 0.1. The rule that follows: never compare floats that come out of arithmetic with ==. Use math.isclose(a, b), with a relative tolerance of by default, or abs(a - b) <= tol with a tolerance that suits the problem. Above not every integer is representable. Overflow gives inf, not an error, and NaN ("not a number") is not equal even to itself. The course Computer Architecture and Operating Systems goes through the bits.
bool. True and False are the only two objects of type bool, a subclass of int. In arithmetic True is 1 and False is 0. Comparisons such as loss > 0.5 produce a bool, so the number of items that pass a test is the sum of the tests.
None. None is the single object of type NoneType. It means "no value here". A function that ends without return returns None, and print is one of them:
print(True + True, isinstance(True, int))
print(sum([0.8 > 0.5, 0.3 > 0.5, 0.9 > 0.5]))
result = print("hi")
print(result is None)2 True
2
hi
TrueThe REPL does not display a None result. That is why print("hello") showed nothing but hello in the topic Running Python.
Dynamic but 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 to a str later, and nothing is checked before the program runs:
x = 5
print(type(x))
x = "five"
print(type(x))
print(1 + 2.5, True + 1, "3" * 4)<class 'int'>
<class 'str'>
3.5 2 3333Strong typing. Each operation checks the types of its operands at the moment it runs, and Python does not silently convert between unrelated types. Here is the loose end from Running Python. Save this as train.py and run python train.py 10:
import sys
epochs = sys.argv[1]
print(type(epochs), int(epochs) + 1)
print(epochs + 1)<class 'str'> 11
Traceback (most recent call last):
...
TypeError: can only concatenate str (not "int") to strThe argument is a str. Adding a number to it is an error, not '101' and not 11. The conversion has to be written: int(epochs). The exceptions are deliberate and few. Numbers mix freely, so 1 + 2.5 turns the int into a float, and bool counts as an int. "3" * 4 is not a conversion at all but an operation of strings, repetition. Since types are checked only when a line runs, many errors show up only then. That is one reason for the topics Testing and Type hints later in the course.
Every program in these two topics ran each of its lines exactly once, from top to bottom. Real programs must choose: save the model only if loss < best. And they must repeat: one training step for every batch. The bool that a comparison produces is the raw material for both. The next topic, Control flow, introduces if, while, for and match, and shows how if asks any object, not only a bool, whether it counts as true.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Go deeper — optional
Code and labs do not count toward the main percentage or the certificate.
- An expression for a discounted purchaseoptional
Write one line and get a static check. Code is not executed; you can try it on a phone.
~5 min · any device · Read the block about values and arithmetic operations. The function wrapper is provided.
Answers are saved on the server and tied to this browser until you sign in.