Course outline · 0% complete

0/32 lessons0%

Course overview →

Working Over a Whole List

lesson 6-3 · ~12 min · 19/32

Built-ins that eat a whole list

Totals, averages, biggest and smallest: every report, invoice, and dashboard boils a list down to a few numbers. The loops for these are so common that Python ships them as built-in functions, so the hand-written loop disappears.

Python ships helpers so common loops disappear:

scores = [85, 92, 78, 90, 88]
sum(scores)      # 433
min(scores)      # 78
max(scores)      # 92
len(scores)      # 5
sorted(scores)   # [78, 85, 88, 90, 92]  new list

Sorting has a famous trap. sorted(lst) returns a new sorted list. lst.sort() sorts in place and returns None. So:

nums = [3, 1, 2]
nums = nums.sort()   # BUG: nums is now None

Either call nums.sort() on its own line, or use nums = sorted(nums). Never mix the two styles.

Code exercise · python

Run this. Note that `sorted()` leaves the original list untouched, and the average combines `sum` and `len` from the loop patterns you hand-wrote in lesson 5-3.

Quiz

What does this print? ```python nums = [3, 1, 2] nums = nums.sort() print(nums) ```

Code exercise · python

Run the filter-build combo, the single most common list pattern in working code: build a NEW list holding only the items that pass a test. Search results, permission checks, and report filters are this exact shape with bigger data.

Code exercise · python

Your turn. Without using sum() or max(), use one loop to find both the total and the biggest value in `nums`, then print them separated by a space. (Real interviews ask for exactly this.)

Problem

Trace by hand: ```python nums = [3, 1, 2] nums.append(5) nums.pop(0) print(nums) ``` What exactly is printed? Write it as Python would, brackets included.