…
…
Python Programming Fundamentals · Lesson 31 / 40 · Functions as values
PreviewIn this lesson you will
sorted, max, and min order or pick records of a list by a chosen measure with keylambda, and choose def for a measure with several stepsYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The day is over, and Ada is looking at the order records at the register. She wants two things: to see the orders by total from largest to smallest, and to find the most expensive item on the menu in a single line. In this lesson you will learn to tell Python "by what" to sort, by passing a function around like a value without calling it.
The program you will write at the end of the lesson will list the end-of-day orders by total, from largest to smallest, like this:
Outputlatte $8.50
tea $3.75
water $3.00
cookie $2.00The data is the list of records you met in lesson 28 and the menu dictionary from lesson 26:
orders = [
{"item": "latte", "qty": 2, "price": 4.25},
{"item": "tea", "qty": 3, "price": 1.25},
{"item": "cookie", "qty": 1, "price": 2.00},
{"item": "water", "qty": 4, "price": 0.75},
]
menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25, "water": 0.75}The first idea is the sorted function you learned in lesson 24. It sorted lists of numbers and strings. Will it sort a list of records too? Let's try:
print(sorted(orders))
Error:
OutputTypeError: '<' not supported between instances of 'dict' and 'dict'Python does not know which of two dictionaries is "smaller". Is the latte record smaller, or the tea record? Should it look at the name, the quantity, or the total? Python cannot make this decision; you have to tell it. The way to tell it is a function: "Apply this function to each record and sort by the numbers that come out." To do that, we first need to look at functions in a new way.
In this lesson you will:
sorted, max, and min which measure to look at with key.lambda.This lesson is marked "Advanced"; it does not lock your progress. Still, the key pattern you learn here will help you in almost every report you write later.
Until now you have always called functions: len("latte"), print(...), total(order). When you put parentheses after a name, Python runs the function right away and puts its result in its place. But what happens if you do not write the parentheses at all? Then Python does not run the function; it holds the function itself as a value. Just like the number 0.75 or the string "latte", a function can be put in a variable, added to a list, or passed to another function as an argument.
Example 1 (case): A name with and without parentheses
print(len) size = len print(size("latte"))
Output<built-in function len>
5The first line does not call len; it only prints what it is: "built-in function len". In the second line, the len function itself is put in the size variable. Now the same function has two names; writing size("latte") does the same job as len("latte") and returns 5. Functions you write yourself behave the same way. Let's write a function that calculates the total of an order:
def total(order): return order["qty"] * order["price"] print(total) print(total(orders[0]))
When you run this code, you see two lines like these:
Output<function total at 0x...>
8.5The 0x... part in the first line is the address of the function in memory; it is a different number every time you run the code, so we show it with dots here. The important point is this: writing total gives you the function itself, and writing total(orders[0]) gives you the total of the latte order, 2 × 4.25 = 8.5.
Since functions are values, they can also be put in a list. Imagine that at the café you want to add sales tax to an amount first, and then apply a discount to the same amount. You can put the two operations in a list and apply them one after the other with a loop:
Example 2 (case): A list of functions
def add_tax(amount): return round(amount * 1.1, 2) def discount(amount): return amount * 0.9 for operation in [add_tax, discount]: print(f"${operation(5):.2f}")
Output$5.50
$4.50In the first turn of the loop, the operation variable holds the add_tax function, and operation(5) is really add_tax(5). In the second turn, the variable holds discount. Notice that we wrote add_tax in the list, not add_tax(): we put the function itself in the list, not its result. The loop calls it whenever it wants.
In the matching exercise below, choose what each expression gives. Is it the function itself, a result, or an error?
The total function is defined as above, and size = len has run first. What does each expression give?
For each row, pick its match from the list, then check.
lenlen("latte")totaltotal(orders[0])size("tea")total()The point that gets mixed up most often is this: "passing a function" and "calling a function" are different jobs. When you pass a function somewhere, you do not write parentheses; the side that uses it puts the parentheses. Keep this in mind, because the rest of the lesson is built on this idea.
keyThe sorted function has a named argument called key. You met named arguments in lesson 15; reverse=True was a named argument too. You give key a function. sorted calls this function itself for each item in the list, notes the values that come back, and arranges the items by these values. The list you get back still contains the items themselves; the values the function returns are used only as a measure in the sorting and do not go into the result.
Let's see it with a list of product names. First without key, then with key=len, and last from largest to smallest:
Example 3 (case): The same list, three orderings
items = ["cookie", "tea", "latte", "milk"] print(sorted(items)) print(sorted(items, key=len)) print(sorted(items, key=len, reverse=True))
Output['cookie', 'latte', 'milk', 'tea']
['tea', 'milk', 'latte', 'cookie']
['cookie', 'latte', 'milk', 'tea']Read the three lines one by one. Without key, strings are arranged alphabetically. With key=len, Python calls len(name) itself for each name: cookie 6, tea 3, latte 5, milk 4. The sorting is done by these numbers, but the list holds the names, not the numbers: the shortest, tea, comes first and the longest, cookie, comes last. reverse=True keeps the same measure and only reverses the order. The list was the same in all three calls; the only thing that changed was what Python looked at. (In the third line the result happens to match the alphabetical order, but it comes from the lengths 6, 5, 4, 3.)
Predict first: which word does the code below print?
What does this code print?
words = ["bagel", "tea", "latte"] print(sorted(words, key=len)[0])
Now let's go back to the case. To sort the records by total, we already have a function that calculates the total: total. We pass it to key without parentheses. sorted will call total(record) itself for each order record and arrange the records by the numbers 8.5, 3.75, 2.0, 3.0. With reverse=True the order will be from largest to smallest. This is the target program of the lesson:
Example 4 (case): The target program of the lesson
orders = [
{"item": "latte", "qty": 2, "price": 4.25},
{"item": "tea", "qty": 3, "price": 1.25},
{"item": "cookie", "qty": 1, "price": 2.00},
{"item": "water", "qty": 4, "price": 0.75},
]
# 1. Write the measure as a function
def total(order):
return order["qty"] * order["price"]
# 2. Sort by the measure, largest to smallest
for o in sorted(orders, key=total, reverse=True):
# 3. Print aligned
print(f"{o['item']:<9}${total(o):.2f}")Outputlatte $8.50
tea $3.75
water $3.00
cookie $2.00The o in the loop is an order record in each turn, not a total. To print the total, this time we call o's total ourselves with total(o). The same function was used twice in two different ways: in the key=total part without parentheses (it is passed to the sorting), in the print line with parentheses (its result is printed). The alignment is the formatting from lesson 22: :<9 pads the name to a field of 9 characters and aligns it to the left, and .2f shows the total with two decimal places.
One more detail: if two items get the same value from key, the sorting keeps their first order in the list. This is called stable sorting. In a moment you will see it clearly in the class list example.
max and min take the same key argument. max(list, key=f) gives "the item with the largest f value". This is very handy with dictionaries: when you walk through a dictionary, the keys come. When you write max(menu, key=menu.get), Python calls menu.get(name) for each product name, compares the prices, and returns the name of the product with the highest price. menu.get is also written without parentheses; we pass the dictionary's get method as a function.
Example 5 (case): The two ends of the menu and the price order
menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25, "water": 0.75}
print(max(menu, key=menu.get))
print(min(menu, key=menu.get))
print(sorted(menu, key=menu.get))Outputlatte
water
['water', 'tea', 'cookie', 'latte']Step through the code below. After each line runs, look at the variable boxes: do the ranked, priciest, and shortest boxes hold a price or a product name? Then use "Change the code" to add "water": 0.75 to the menu and step through it again.
Run the code line by line: see which line runs next, the variable boxes and the output.
menu = {"tea": 1.25, "latte": 4.25, "cookie": 2.00}
ranked = sorted(menu, key=menu.get)
priciest = max(menu, key=menu.get)
shortest = sorted(menu, key=len)
print(ranked)
print(priciest, shortest)The boxes always hold product names. key sets the measure of the sorting; it does not transform the result. If you need the prices, you read them separately: for example menu[priciest].
So what happens if you forget key? max(menu) works too and raises no error; but what does it return? Predict.
With menu = {"tea": 1.25, "latte": 4.25, "cookie": 2.00}, what does this line print?
menu = {"tea": 1.25, "latte": 4.25, "cookie": 2.00}
print(max(menu), max(menu, key=menu.get))Now change the measure and see what happens. The code below has three measure functions: total, get_qty, and get_name. Whichever you put in the measure variable, the sorting is done by that. The last button shows what writing total(), that is, calling the function instead of passing it, does.
Put different functions in the measure variable. How does the order change? What happens with the last button?
Pick a value; predict the output first, then look.
1orders = [2 {"item": "latte", "qty": 2, "price": 4.25},3 {"item": "tea", "qty": 3, "price": 1.25},4 {"item": "cookie", "qty": 1, "price": 2.00},5 {"item": "water", "qty": 4, "price": 0.75},6]7def total(order):8 return order["qty"] * order["price"]9def get_qty(order):10 return order["qty"]11def get_name(order):12 return order["item"]13measure = total14ranked = sorted(orders, key=measure)15for o in ranked:16 print(o["item"], measure(o))
cookie 2.0 water 3.0 tea 3.75 latte 8.5
Faded lines didn't run with this value. The records did not change at all; only the value sorted looks at changed. With get_name the items are arranged alphabetically. When you write total(), Python tries to run the function at that moment, without an argument; the order parameter stays empty, so it raises TypeError and the later lines never run. To pass a function, you do not write parentheses.
Read the error message on the last button carefully: total() missing 1 required positional argument: 'order', that is, "a required argument is missing in the total() call: order". Python is telling you, "you called the function but did not say what to give it." The same error comes when you write sorted(orders, key=total()); we will return to it in the "Common mistake" section at the end of the lesson.
lambda: a small function without a nameIf you will use a measure like total in several places, it is good to write it with def and give it a name. But sometimes a measure is so small and needed only once that writing a separate def for it feels like too much. For example, to sort the menu pairs by price, "take the second item of the pair" is enough. For this, Python offers the lambda expression: a function made of a single expression, with no name.
lambda pair: pair[1] is read like this: "take pair, return pair[1]." To the left of the colon is the parameter, to the right is the expression to return. You do not write return; the value of the expression on the right comes back by itself. The two forms below do the same job:
With def | With lambda |
|---|---|
def get_qty(o): / return o["qty"] | lambda o: o["qty"] |
def get_price(pair): / return pair[1] | lambda pair: pair[1] |
| Has a name, can be called in many places | Has no name, used where it is written |
Can have several lines, an if block, a loop | Only a single expression |
Example 6 (case): Sorting pairs and records with `lambda`
menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25, "water": 0.75}
orders = [
{"item": "latte", "qty": 2, "price": 4.25},
{"item": "tea", "qty": 3, "price": 1.25},
{"item": "cookie", "qty": 1, "price": 2.00},
{"item": "water", "qty": 4, "price": 0.75},
]
print(sorted(menu.items(), key=lambda pair: pair[1]))
print(max(orders, key=lambda o: o["qty"])["item"])Output[('water', 0.75), ('tea', 1.25), ('cookie', 2.0), ('latte', 4.25)]
waterIn the first line, menu.items() gives the (name, price) tuples from lesson 29; lambda makes the price of each tuple, that is pair[1], the measure. The second line has two steps: first max finds the order record with the largest quantity (water, 4 units), then the ["item"] at the end reads the name of that record. Predict: what would be printed without the ["item"] at the end?
What does this line print?
orders = [
{"item": "latte", "qty": 2, "price": 4.25},
{"item": "tea", "qty": 3, "price": 1.25},
{"item": "cookie", "qty": 1, "price": 2.00},
{"item": "water", "qty": 4, "price": 0.75},
]
print(max(orders, key=lambda o: o["qty"])["item"])lambda works the same way outside the café. Let's say a class's grade list is made of (name, grade) tuples. Let's sort it by grade from largest to smallest and find the student with the highest grade:
Example 7 (outside the case): Class list
students = [("Ella", 88), ("Mark", 72), ("Zoe", 95), ("Sam", 72)] print(sorted(students, key=lambda s: s[1], reverse=True)) print(max(students, key=lambda s: s[1])[0])
Output[('Zoe', 95), ('Ella', 88), ('Mark', 72), ('Sam', 72)]
ZoeMark and Sam have the same grade: 72. In the sorting Mark comes first, because he was first in the list too. Stable sorting keeps the old order of items with an equal measure; this rule is not broken when reverse=True is given either.
Now let's make the border between def and lambda clear. A lambda can take only a single expression: you cannot write an if block, a loop, or several separate steps inside it. If the measure has several steps, like "first apply the discount, then add sales tax, then round", or if you will use the same measure in three different places in the program, write it with def and give it a meaningful name. Remember from lesson 19: a function with a name can be tested on its own, and its bug is fixed in one place. Keep lambda for measures you read at a glance, like "look at this field".
Put the lines of the target program in the right order. Think about which line must come before which: a function must be defined before it is used.
Put the lines of the program that prints the orders by total, from largest to smallest, in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Your turn. In the cell below, Example 7 is ready. Try three things: (1) Find the student with the lowest grade. (2) Sort alphabetically by name; the measure will be lambda s: s[0]. (3) Why did the order of Mark and Sam not change? Swap their places in the list and run it again.
Try it now· not graded; doesn't affect progress
map, filter, any, all (not in the test)There are other built-in tools that take a function; you will see them often in other people's code, so recognizing them is enough. map(f, list) applies f to each item of the list. filter(f, list) keeps only the items for which f returns true. Neither gives its result as a list right away; they return a lazy object that produces the items when asked, and to see inside it you turn it into a list with list(...). any(...) gives True if at least one value is true, and all(...) gives True if all of them are.
Example 8: Four tools together
prices = [4.25, 2.00, 1.25, 0.75] print(list(map(lambda p: p + 0.50, prices))) print(list(filter(lambda p: p < 3, prices))) print(any([p > 4 for p in prices]), all([p > 1 for p in prices])) print(list(map(int, "3,1,2".split(","))))
Output[4.75, 2.5, 1.75, 1.25]
[2.0, 1.25, 0.75]
True False
[3, 1, 2]The list comprehension from lesson 30 also does the job of the first two lines, and it is often more readable: [p + 0.50 for p in prices] and [p for p in prices if p < 3]. map is short and clear when it applies a ready-made function (int), as in the last line. Try it below: delete the list(...) from the map line and run it, and look at what it prints. Write the same two lines with a comprehension. Change the threshold in the all line to 0.5 and run it again.
Try it now· not graded; doesn't affect progress
Three ideas together: a measure function (total), key=menu.get on a dictionary, and a one-time lambda. Ada's end-of-day note comes out in a few lines.
orders = [
{"item": "latte", "qty": 2, "price": 4.25},
{"item": "tea", "qty": 3, "price": 1.25},
{"item": "cookie", "qty": 1, "price": 2.00},
{"item": "water", "qty": 4, "price": 0.75},
]
menu = {"latte": 4.25, "cookie": 2.00, "tea": 1.25, "water": 0.75}
# 1. The measure function
def total(order):
return order["qty"] * order["price"]
# 2. Answer the questions with key
top_revenue = max(orders, key=total)
top_qty = max(orders, key=lambda o: o["qty"])
priciest = max(menu, key=menu.get)
# 3. Print the report
(f)
(f)
(f)Passing the result of the function to `key`. Because you are used to using functions, writing key=total() feels very natural:
ranked = sorted(orders, key=total())Error:
OutputTypeError: total() missing 1 required positional argument: 'order'When it sees the parentheses, Python tries to run total at that moment, without giving it any argument. The order parameter stays empty, so it raises an error. But sorted wanted the function itself, and it would call it itself for each record. The right way: sorted(orders, key=total).
total), a name with parentheses runs it and gives its result (total(o)); a function can be given as a value to a variable, a list, or another function.sorted, max, and min pass each item through the function in key and compare by the value that comes back; the items themselves stay in the result, items with an equal value keep their old order, and reverse=True arranges from largest to smallest.lambda o: o["qty"] is a one-expression function without a name, for one-time measures; a measure with several steps, or one used in several places, is written with a named def.Next lesson: Unit 6 is done; the next stop is the Corner Café receipt with a menu dictionary and a cart (the unit project), and then you move on to files, where the first job is to write a function that does not crash on bad input.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputTop revenue: latte $8.50
Most units: water 4
Priciest on the menu: latte $4.25The key=dictionary.get pattern works with any "name → number" data.
temperature = {"Lima": 19, "Cairo": 28, "Oslo": 3, "Sydney": 24}
print(max(temperature, key=temperature.get))
print(min(temperature, key=temperature.get))
print(sorted(temperature, key=temperature.get, reverse=True))OutputCairo
Oslo
['Cairo', 'Sydney', 'Lima', 'Oslo']for s in ranked:TypeError: 'NoneType' object is not iterablesorted(...)