1.3. Common Patterns#
Some Python patterns appear in almost every program you will read, long before you are ready to write them. This section shows seven of them. You do not need to master them now. Read each one aloud, run it, and notice its shape. Each pattern is taught in detail in a later chapter, named in its subsection.
1.3.1. Context Managers#
A context manager sets something up, lets you use it, and cleans up afterward, even if an error occurs. The with statement runs one. Files are the most common case: with open(...) as f: closes the file as soon as the indented block ends. Read it as “with this file open, do the following.” Chapter 8 reads files this way, and Chapter 10 explains context managers and shows how to write your own.
Syntax (a pattern, not runnable code):
with expression as name:
block that uses name
open(path, mode) # a common expression to use after "with"
expression creates the context manager, and name holds what it hands back; for a file, that is the open file. The indented block runs while the resource is in use, and the cleanup runs when the block ends. For open(), path is the file’s location and mode is "r" to read (the default), "w" to write, or "a" to append.
The example stores its file in the book’s data folder. The setup cell at the top of the notebook provides project_root.
data_dir = project_root / "data"
data_dir.mkdir(parents=True, exist_ok=True)
notes_file = data_dir / "notes.txt"
with open(notes_file, "w") as f: # "w" means write
f.write("apples\nbananas\n")
with open(notes_file) as f: # the default mode is read
print(f.read())
apples
bananas
1.3.2. List Comprehensions#
A list comprehension builds a new list from an existing one. Read [p * 2 for p in prices] as “p times 2, for each p in prices.” Adding an if at the end keeps only the items that pass the test. Chapter 6 covers comprehensions.
Syntax (a pattern, not runnable code):
[expression for item in iterable]
[expression for item in iterable if condition]
iterable is anything you can loop over, such as a list, a string, or a range. Python takes each item in turn, and expression (usually built from item) becomes one element of the new list. With if, only the items for which condition is true are kept. The original sequence is not changed.
prices = [1.25, 0.5, 2.75, 3.1, 0.89]
print([p * 2 for p in prices])
print([p for p in prices if p < 1])
[2.5, 1.0, 5.5, 6.2, 1.78]
[0.5, 0.89]
1.3.3. Lambda Expressions#
A lambda expression is a function with no name, written on one line. Read lambda name: len(name) as “given name, return its length.” A lambda is most often passed as the key argument that tells sorted() what to sort by. Chapter 4 covers functions and lambdas.
Syntax (a pattern, not runnable code):
lambda parameters: expression
parameters are the inputs, separated by commas if there is more than one (lambda a, b: a + b). expression is the single value the function returns; there is no return keyword, and the body cannot hold more than one expression. It does the same job as a def function whose body is one return line.
fruits = ["apple", "banana", "cherry", "durian", "elderberry"]
print(sorted(fruits, key=lambda name: len(name)))
['apple', 'banana', 'cherry', 'durian', 'elderberry']
1.3.4. Conditional Expressions#
A conditional expression picks one of two values. Read "pass" if score >= 60 else "fail" as “pass, if the score is at least 60; otherwise fail.” Chapter 3 covers conditionals.
Syntax (a pattern, not runnable code):
value_if_true if condition else value_if_false
Python evaluates condition first. If it is true, the whole expression has the value value_if_true; otherwise it has the value value_if_false. Because it produces a value, you can assign it to a variable or use it inside print() or an f-string, which an if statement cannot do.
score = 83
print("pass" if score >= 60 else "fail")
pass
1.3.5. Unpacking and Expansion#
1.3.5.1. Unpacking#
Unpacking takes an iterable apart and assigns its items to several variables in one statement:
x, y = (3, 4) # x = 3, y = 4
Python pulls the items one at a time, so unpacking works with any iterable (lists, tuples, strings, ranges, sets, generators), not only tuples. There are two kinds:
Plain unpacking assigns items to variables by position. The number of variables must equal the number of items, or Python raises a
ValueError.Starred unpacking puts
*in front of one variable, which collects all leftover items into a list. The list may be empty, and only one starred variable is allowed per assignment.
a, b, c = [10, 20, 30] # a = 10, b = 20, c = 30
a, b = b, a # swap: a = 20, b = 10
first, *rest = [1, 2, 3, 4] # first = 1, rest = [2, 3, 4]
head, *mid, tail = "python" # head = 'p', mid = ['y', 't', 'h', 'o'], tail = 'n'
a, *b = [1] # a = 1, b = []
a, b = [1, 2, 3] # ValueError: too many values to unpack
1.3.5.2. Expansion#
Expansion works in the opposite direction: instead of collecting items into a variable, * and ** spread items out into a new collection or a function call.
Iterable expansion (
*) spreads the items of any iterable into a list, tuple, or set literal, or into the positional arguments of a function call. You can use several*in one expression.Dictionary expansion (
**) spreads a dictionary’s key-value pairs into a dictionary literal or into the keyword arguments of a function call.
a, b = [1, 2], (3, 4)
[*a, *b] # [1, 2, 3, 4] (works even though a and b are different types)
print(*"abc") # a b c
defaults = {"color": "red", "size": 1}
user = {"size": 3}
{**defaults, **user} # {'color': 'red', 'size': 3}
def area(width, height):
return width * height
dims = {"width": 4, "height": 5}
area(**dims) # same as area(width=4, height=5) → 20
area(**dims, width=2) # TypeError: got multiple values for argument 'width'
Tip: On the left side of
=,*collects items into a list. On the right side or in a function call,*spreads items out.
point = (3, 4)
x, y = point
print(x, y)
quotient, remainder = divmod(17, 5)
print(quotient, remainder)
fruits = [ "apple", "banana", "cherry", "durian" ]
first, *others = fruits
print(first)
print(others)
3 4
3 2
apple
['banana', 'cherry', 'durian']
1.3.6. enumerate() and zip()#
enumerate() pairs each item with its position, and zip() walks two sequences together. Both usually appear on a for line, which repeats the indented block once per item. Chapter 3 covers for loops.
Syntax (a pattern, not runnable code):
for item in iterable:
block
for index, item in enumerate(iterable, start=0):
block
for item1, item2 in zip(iterable1, iterable2):
block
A plain for loop sets item to each element of iterable in turn. enumerate() produces (index, item) pairs, and start sets the first number (the default is 0). zip() produces pairs of items taken from the same position in each iterable, and it stops when the shorter one runs out. Writing two names, index, item, unpacks each pair into two variables, as in the previous subsection.
for i, name in enumerate(fruits, start=1):
print(i, name)
for name, price in zip(fruits, prices):
print(f"{name}: ${price:.2f}")
1 apple
2 banana
3 cherry
4 durian
apple: $1.25
banana: $0.50
cherry: $2.75
durian: $3.10
1.3.7. Exception Handling#
An error that stops a program is an exception. A try statement lets the program recover instead. Read it as “try this; if it fails this way, do that.” Chapter 5 covers exceptions.
Syntax (a pattern, not runnable code):
try:
block that might fail
except ExceptionType:
block that runs if it fails that way
Python runs the try block. If it raises an exception of type ExceptionType, such as ValueError for a bad conversion, Python skips the rest of the try block and runs the except block instead. If nothing goes wrong, the except block is skipped. A try statement can also have else and finally blocks.
text = "12a"
try:
quantity = int(text)
except ValueError:
quantity = 0
print(quantity)
0
### Exercise: Read and predict
# Read the four patterns below without running them.
# Fill in each predicted_ variable with the value the pattern produces.
# Then run the cell. Each line prints True when your prediction is right.
prices = [1.25, 0.5, 2.75, 3.1, 0.89]
fruits = ["apple", "banana", "mango", "kiwi", "fig"]
text = "12a"
actual_prices = [p for p in prices if 1 < p < 3]
actual_fruits = sorted(fruits, key=lambda name: name[-1]) # name[-1] is the last letter
try:
actual_quantity = int(text)
except ValueError:
actual_quantity = 0
first, *actual_others = fruits
### Your code starts here.
predicted_prices = []
predicted_fruits = []
predicted_quantity = None
predicted_others = []
### Your code ends here.
print(predicted_prices == actual_prices)
print(predicted_fruits == actual_fruits)
print(predicted_quantity == actual_quantity)
print(predicted_others == actual_others)
False
False
False
False
True
True
True
True