…
…
Python Programming Fundamentals · Lesson 24 / 40 · Lists
PreviewIn this lesson you will
enumerate and in pairs using zipYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Ada wants to write the three most expensive prices and the average price of the menu on Corner Café's display board, and she wants to show the menu with numbers. The prices are in one list and the product names are in another. She has one condition: the original order of the menu at the register must not change.
In the last lesson you learned to build a list, reach its elements with an index, and change it with append, remove, and pop. Now you have a full list and you want to get information out of it: what is the total, which item is the most expensive, how does it look when sorted? In lesson 12 you could answer all of these with a loop, building up the answer step by step. But Python gives you built-in tools for the jobs you do most often with lists. The two small functions you will write at the end of the lesson will produce this output:
OutputTop three: [4.25, 2.0, 1.75]
Average: 2.0
Menu unchanged: [4.25, 2.0, 1.25, 1.75, 0.75]Look at the last line: we sorted for the board, but the menu at the register stays as it was. This is the most important idea of the lesson.
In this lesson you will be able to:
sum, min, max, and len, and find its average.enumerate and loop over two lists as pairs using zip.In lesson 12 we built a piggy bank to find the day's revenue: we started with total = 0, added the price in every round of the loop, and printed the result when the loop ended. For the highest price we kept a record variable in a similar way. These patterns are still important, because sometimes you need to accumulate with a condition. But if the values are already in a list and you only need the total or the largest, one function does the same job.
There are four summary functions. sum(list) gives the total of the elements, min(list) the smallest, max(list) the largest, and len(list) the number of elements. You know len from strings; for a list it counts elements instead of characters. All four reduce the list to a single value and do not touch the list. For the average you do not need a separate function: you divide the total by the count, that is, sum(prices) / len(prices).
Example 1 (case): Price summary
prices = [4.25, 2.00, 1.25, 1.75, 0.75] print(sum(prices), min(prices), max(prices), len(prices)) print(f"Average: ${sum(prices) / len(prices):.2f}")
Output10.0 0.75 4.25 5
Average: $2.00All the prices are floats, so the total is a float too: 10.0. The average is 10.0 / 5 = 2.0; with the :.2f from lesson 22 we wrote it with two decimal places. (Python drops trailing zeros, so 2.00 in the list prints as 2.0 when you print the list.)
In the cell below, two ways stand side by side: the loop from lesson 12 on top, the built-in functions below. First run it and see that both lines print 10.0 4.25. Then do the tasks in the comments.
Try it now· not graded; doesn't affect progress
You also need to know the limits of the built-in functions. min and max work on a list of strings too, and give the string that comes first or last in alphabetical order: min(["water", "latte"]) is latte. sum, however, only adds numbers. If you write sum(["latte", "tea"]) you get TypeError: unsupported operand type(s) for +: 'int' and 'str'. The message may look odd: why does it say int when there is no integer in the list? Because sum, like your piggy bank, starts from 0 and tries to add the first string to 0; a number and a string cannot be added.
The second limit is the empty list. If the day has opened but there are no sales yet, the list is []. sum([]) gives 0 and len([]) gives 0, so far no problem. But max([]) cannot find a largest, because there are no elements at all: ValueError: max() iterable argument is empty. For the average, 0 / 0 is attempted and the program stops with ZeroDivisionError. So before taking the average of a list that might be empty, you ask if len(list) == 0:. The average function at the end of the lesson will do exactly that.
Now match which question is answered by which tool. One option has been added extra; it looks like the average but is not.
Pick the right expression for each task.
For each row, pick its match from the list, then check.
count in the last match is a list method. The table below collects three small tools that go with it. They bring no new idea, but you only need to know them well enough to recognize them.
| Tool | What it does | Example (prices = [4.25, 2.00, 1.25, 1.25]) |
|---|---|---|
list.count(x) | How many times x appears | prices.count(1.25) → 2 |
list.index(x) | Index of the first x; ValueError if missing | prices.index(1.25) → 2 |
list.extend(other) | Adds the elements of the other list to the end, returns None | prices.extend([2.50, 0.75]) |
sort or sorted?On the board the prices should look sorted, but the order of the menu at the register must not change; the cashier knows the products by that order. Python has two ways to sort, and the difference between them touches exactly this need.
list.sort() is a method. The rule from lesson 23 applies here too: list methods change the list in place and return None. After prices.sort() runs, prices is sorted; the original order is lost. sorted(list) is a function: it does not touch the list and returns a new sorted list. If you want to use it, you assign it to a variable or print it directly. Both sort from smallest to largest; for largest to smallest you give the named argument reverse=True. Remember from lesson 15: a named argument says by name which value goes where. There are also two ways to reverse a list without sorting it; the table puts all four side by side.
| Tool | What it returns | Original list |
|---|---|---|
list.sort() | None | Sorted |
sorted(list) | New sorted list | Unchanged |
list.reverse() | None | Reversed |
list[::-1] | New reversed list | Unchanged |
When choosing, ask yourself one question: will I need the original order again later? If so, use sorted. If you will not use the list in its original order again, sort is fine, and since it does not create a separate list it does not use extra memory.
Example 2 (case): Two ways side by side
prices = [4.25, 2.00, 1.25, 1.75, 0.75] print(sorted(prices)) print(prices) prices.sort(reverse=True) print(prices)
Output[0.75, 1.25, 1.75, 2.0, 4.25]
[4.25, 2.0, 1.25, 1.75, 0.75]
[4.25, 2.0, 1.75, 1.25, 0.75]The second line proves that sorted did not touch the menu. In the third line, sort permanently arranged the menu from largest to smallest; the original order is gone. Integers and floats can be sorted together in one list without trouble.
Now test the most common misunderstanding. Predict before you run the code.
What does this code print?
prices = [2.00, 4.25, 0.75]
ranked = prices.sort()
print(ranked)Step through the code below. In each line, watch the box that changes, especially the ranked box: it appears on line 2, and after that it never changes no matter how much numbers changes. This is because sorted gave a new list of the sorted state at that moment; the two lists are now independent of each other.
Run the code line by line: see which line runs next, the variable boxes and the output.
numbers = [3, 1, 2] ranked = sorted(numbers) numbers.append(5) last = numbers.pop() numbers.sort() print(numbers, ranked, last)
Now it is your turn. Touch the price list below with the buttons. First press sorted: Python shows a sorted list but the boxes stay in place. Then press sort: the answer is None, but the boxes change places. The last button is a deliberate mistake; it asks for the index of a value that is not in the list.
Sort, summarize, and search the price list (prices in cents). Watch the difference between sorted and sort.
Press an operation; predict what Python will say first.
No operations yet. Press a button above.
What Ada really wants is not the whole sorted list but the three most expensive prices. For this you use two tools you already know, one after the other: first you get a new list from largest to smallest with sorted(prices, reverse=True), then you cut the first three with the slice you saw on strings in lesson 20: [:3]. Python reads this expression from left to right: sorted(...) runs first and produces a list, and the slice is applied to that new list. The menu is never touched at any stage.
Example 3 (case): The three most expensive prices
prices = [4.25, 2.00, 1.25, 1.75, 0.75] top_prices = sorted(prices, reverse=True)[:3] print(top_prices) print(prices)
Output[4.25, 2.0, 1.75]
[4.25, 2.0, 1.25, 1.75, 0.75]What if the menu has fewer than three products? As with strings, a slice on a list does not raise an error when it runs past the end; it gives whatever there is. [2.00][:3] is [2.0]. This is good news: your function works on short lists without crashing. Below, change how many prices are chosen with n and the direction of the sort with descending. Try all eight combinations; look especially at n = 6: the menu has 5 prices, but there is no error.
Which prices are chosen when n and descending change?
Pick a value; predict the output first, then look.
1prices = [4.25, 2.00, 1.25, 1.75, 0.75]2n = 33descending = True4chosen = sorted(prices, reverse=descending)[:n]5print("Chosen:", chosen)
Chosen: [4.25, 2.0, 1.75]
Faded lines didn't run with this value. When descending = False, reverse=False is used and the cheapest come first. n = 6 is more than the 5 prices on the menu, but a slice that runs past the end does not raise an error; it gives the whole list. reverse is an argument that takes a true/false value; the value can come from a variable too.
Sorting works not only on numbers but also on strings, but it has a surprise. Python orders strings not alphabetically but by the Unicode number of each character. The letters a to z have consecutive numbers, and so do A to Z, but all the capital letters have smaller numbers than the lowercase ones. So even Z comes before a: sorted(["tea", "Mocha", "latte"]) gives ['Mocha', 'latte', 'tea']. This is not a bug, it is Python's rule; if you do not know it, you will be surprised when a menu you thought was in alphabetical order puts a capitalized name first. To ignore the case, give a function to the named argument key: sorted(words, key=str.lower) compares the lowercase versions of the strings and returns the original strings.
What does this code print?
print(sorted(["water", "tea", "latte", "Mocha"]))
The same tools are not special to the café. Finding the best two scores of a class and the average is the same two lines.
Example 4 (outside the case): Exam scores
scores = [72, 95, 58, 88, 64] best_two = sorted(scores, reverse=True)[:2] print("Best two:", best_two) print("Average:", round(sum(scores) / len(scores), 1)) print("Original list:", scores)
OutputBest two: [95, 88]
Average: 75.4
Original list: [72, 95, 58, 88, 64]377 / 5 = 75.4. We rounded to one decimal place with round. The original order of the scores (perhaps student number order) was kept.
enumerate and zipThe board's second job is to show the menu with numbers: 1 latte, 2 cookie, 3 tea. As in lesson 12, you could do this by opening a counter outside the loop and writing number += 1 in every round. It works, but it is easy to forget to increase the counter or to increase it in the wrong place. enumerate does this for you: when you write for number, item in enumerate(items, start=1):, the loop gives two values in every round, the number and the element. These two values are put into the two names you write after for, separated by a comma. Be careful: if you do not write start, the numbers begin at 0, because Python counts like an index. If you want numbers that people will read on a menu, give start=1.
The third job is to write each product with its price. The names are in the items list and the prices in the prices list; the element at the same index belongs to the same product. zip(items, prices) pairs the elements at the same position of the two lists: the first product with the first price, the second product with the second price. The order of the loop variables is the order of the lists you gave to zip: for item, price in zip(items, prices):. If you mix up the order, Python does not complain; the name item gets the prices and the name price gets the products.
If you print what enumerate and zip produce directly, you see a meaningless object name; if you want to see inside, you turn it into a list with list(...). list(zip(["latte", "tea"], [4.25, 1.25])) gives [('latte', 4.25), ('tea', 1.25)]. These pairs in normal parentheses are called tuples; we will see them in detail in lesson 29.
Example 5 (case): Numbered menu and menu with prices
items = ["latte", "cookie", "tea"] prices = [4.25, 2.00, 1.25] for number, item in enumerate(items, start=1): print(number, item) for item, price in zip(items, prices): print(f"{item}: ${price:.2f}")
Output1 latte
2 cookie
3 tea
latte: $4.25
cookie: $2.00
tea: $1.25Example 5 is ready below. Make the two changes in the comment and watch how the output changes each time.
Try it now· not graded; doesn't affect progress
zip has a property that can put you in a difficult spot. What happens if Ada adds a new product to the menu and forgets to add its price? Predict first.
What does this code print?
items = ["latte", "cookie", "tea"] prices = [4.25, 2.00] for item, price in zip(items, prices): print(item, price)
A silent loss is more dangerous than an error: the program runs, the output looks fine, but the tea has disappeared from the menu. This is the weak point of keeping two separate lists tied to each other: if you add to one and forget the other, the pairing slips. In lesson 26 we will solve this problem at the root by keeping the product with its price in one structure, a dictionary. Until then, be careful to update the two lists together.
Now you have all the parts of the target program. As you have done since lesson 14, we put each job in its own function: one returns the three most expensive prices, the other returns the average. Both functions read the list but do not change it; that is why we use sorted. The average first checks the length so that it does not raise ZeroDivisionError on an empty list. The steps are numbered with comments; you will use the same steps in the exercises.
Example 6 (case): Board summary
def top_three(prices): # 1. Get a new sorted list from largest to smallest ranked = sorted(prices, reverse=True) # 2. Return the first three return ranked[:3] def average(prices): # 3. Return 0 on an empty list if len(prices) == 0: return 0 # 4. Divide the total by the count, round to 2 decimals return round(sum(prices) / len(prices), 2) menu = [4.25, 2.00, 1.25, 1.75, 0.75] print("Top three:", top_three(menu)) print("Average:", average(menu)) print("Menu unchanged:", menu) print(average([]), top_three([2.00]))
OutputTop three: [4.25, 2.0, 1.75]
Average: 2.0
Menu unchanged: [4.25, 2.0, 1.25, 1.75, 0.75]
0 [2.0]The last line tries two edge cases: the average of an empty list is 0 instead of an error, and the "top three" of a one-product menu is only that product. As you learned in lesson 19, it is a good habit to test a function with edge inputs as well as normal ones.
Put the lines of the average function in the right order. Think about where the empty list check should stand.
Build the average function: it returns 0 on an empty list, otherwise the average rounded to 2 decimals.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
extend, count, indexAda adds two new prices to the menu, then checks how many products cost $1.25 and where the first one stands. extend lengthens the list in place; count counts, index gives the first position.
prices = [4.25, 2.00, 1.25, 1.75, 0.75] prices.extend([1.25, 2.50]) print(prices) print(prices.count(1.25)) print(prices.index(1.25))
Output[4.25, 2.0, 1.25, 1.75, 0.75, 1.25, 2.5]
2
2enumerate and sorted work together: first a new alphabetical list is made, then it is numbered. Because of the Unicode order, Mocha is first. At the end we reverse the original list with a slice; items still does not change. The last line shows key=str.lower, which ignores case.
items = ["latte", "cookie", "Mocha", , ] number, item ((items), start=1): (f) (items[::-1]) ((items, key=.lower))
Assigning the result of `sort` to a variable. To find the three most expensive prices, you sort the list from largest to smallest and put the result in ranked:
prices = [4.25, 2.00, 1.25, 1.75, 0.75] ranked = prices.sort(reverse=True) print(ranked[:3])
OutputTypeError: 'NoneType' object is not subscriptableRead the message piece by piece: NoneType is the type of the value None, and "not subscriptable" means "cannot be reached inside with square brackets". So what you tried to slice is not a list but None. Why? sort sorted the list in place and returned None; ranked was bound to that None. The right way, if the original order should be kept, is ranked = sorted(prices, reverse=True). If you do not need the original order again, you write two separate lines: first only prices.sort(reverse=True), then prices[:3]. But on this path the original order of the menu is lost.
sum, min, max, and len reduce a list to one value; the average is sum / len, and for an empty list you check the length first (max([]) gives ValueError, 0 / 0 gives ZeroDivisionError).list.sort() sorts in place and returns None, sorted(list) gives a new sorted list without touching the original; reverse=True sorts from largest to smallest, [:n] takes the first n, and strings are sorted by Unicode order (capital letters first; key=str.lower ignores case).enumerate(list, start=1) gives the number and the element in every round, zip(a, b) gives the elements at the same position of two lists; zip stops without warning when the shorter list ends.Next lesson: What happens when you give a list another name or send it to a function? In the next lesson we will catch the sneaky bug where two names point to the same list.
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.
Output1. Mocha
2. brownie
3. cookie
4. latte
5. water
['water', 'brownie', 'Mocha', 'cookie', 'latte']
['brownie', 'cookie', 'latte', 'Mocha', 'water']A runner has run five laps on the track, and the times in seconds are in a list. We print the laps with numbers and find which lap was the fastest with index. Since index counts from 0, we add 1 to get the lap number that people will read.
laps = [312, 298, 305, 290, 301] for number, seconds in enumerate(laps, start=1): print(f"Lap {number}: {seconds} s") fastest = min(laps) print(f"Fastest: lap {laps.index(fastest) + 1} ({fastest} s)") print("Average:", round(sum(laps) / len(laps), 1))
OutputLap 1: 312 s
Lap 2: 298 s
Lap 3: 305 s
Lap 4: 290 s
Lap 5: 301 s
Fastest: lap 4 (290 s)
Average: 301.2