Looping Through a List
A for loop runs the same lines once for each item in a list, enumerate() numbers the items as it goes, sum(), min() and max() total and compare a list's numbers, and sorted() hands back a sorted copy while .sort() sorts the list itself.
Apprentice · Python · Updated
After this lesson you can
- Loop through a list with for, and number its items with enumerate()
- Total a list with sum(), find its smallest and largest items with min() and max(), and sort it with sorted() or .sort()
Key takeaways
- A for loop runs its block once for each item in a list, in order, with the loop variable holding the current item.
- enumerate() gives the loop each item's number as well as the item, counting from 0 unless you add start=1.
- sum() adds up a list of numbers, and min() and max() give its smallest and largest items.
- sorted() hands back a new sorted list and leaves the original alone, while .sort() sorts the list itself and hands back None.
Once your values are in a list, you'll want to do the same thing with each of them: print every song in a playlist, add up every item in a shopping cart, find the highest score on a quiz. Looping through a list is one of the most common jobs in programming, and Python gives you a loop that reads almost like English, plus a handful of built-in functions that do the most common loops for you.
The example is a road trip from Chicago to the Grand Canyon: four days of driving, with each day's miles kept in a list.
One line per item, by hand
Here's each day's drive, printed one index at a time:
miles = [470, 540, 355, 330]
print("Day 1:", miles[0])
print("Day 2:", miles[1])
print("Day 3:", miles[2])
print("Day 4:", miles[3])
Day 1: 470
Day 2: 540
Day 3: 355
Day 4: 330
Four days, four lines, each index typed by hand. A fifth day needs a fifth line, and a typo in one index prints the wrong day's miles without any error to tell you.
for: once for each item
You work through a checklist from top to bottom: read a line, do it, move to the next. A for loop does that with a list. for day_miles in miles: (read "for each day_miles in miles") runs the indented block under it once for each item, and each time round, day_miles holds the current item:
miles = [470, 540, 355, 330]
total = 0
for day_miles in miles:
print(day_miles, "miles")
total = total + day_miles
print("Total:", total, "miles")
470 miles
540 miles
355 miles
330 miles
Total: 1695 miles
The loop variable's name is yours to choose. A name for one item, such as stop for an item of stops or day_miles for an item of miles, keeps the loop clear to read. Add a fifth day to the list and the loop handles it with no new line.
enumerate(): the item and its number
Sometimes you need each item's number as well: "Day 1", "Day 2". enumerate() hands the loop two values each time round, the count and the item, and start=1 makes the count begin at 1 instead of 0:
stops = ["Omaha", "Denver", "Moab", "Grand Canyon"]
for day, stop in enumerate(stops, start=1):
print("Day", day, "ends in", stop)
Day 1 ends in Omaha
Day 2 ends in Denver
Day 3 ends in Moab
Day 4 ends in Grand Canyon
day, stop gives the two values a name each; Tuples and Unpacking shows how two names on the left take two values apart. Leave out start=1 and the count starts at 0, the same as an index.
sum(), min() and max()
Adding up a list is so common that Python has a function for it. sum() adds up a list's numbers, and min() and max() give its smallest and largest items:
miles = [470, 540, 355, 330]
print("Total:", sum(miles))
print("Shortest day:", min(miles))
print("Longest day:", max(miles))
print("Average:", sum(miles) / len(miles))
Total: 1695
Shortest day: 330
Longest day: 540
Average: 423.75
The loop that added up the total and sum(miles) give the same 1695; the built-in function is shorter and harder to get wrong. min() and max() on an empty list stop with a ValueError, because an empty list has no smallest item.
sorted() or .sort()
To see the days from shortest to longest, there are two ways, and they differ in one important way. sorted(miles) hands back a new sorted list and leaves miles as it was. miles.sort() sorts miles itself, in place:
miles = [470, 540, 355, 330]
in_order = sorted(miles)
print(in_order)
print(miles)
miles.sort()
print(miles)
[330, 355, 470, 540]
[470, 540, 355, 330]
[330, 355, 470, 540]
Use sorted() when the original order still matters (the days of a trip happen in order, after all), and .sort() when it doesn't. Because .sort() changes the list instead of handing one back, it returns None, and that makes a common trap:
miles = [470, 540, 355, 330]
miles = miles.sort()
print(miles)
None
The list was sorted, and then miles was given the None that .sort() returned. Write miles.sort() on its own line, or miles = sorted(miles).
Do it: find the long driving days
The trip planner flags each day with a long drive, so the travelers can plan an early start.
miles: each day's miles, in order, with day 1 first.limit: the most miles that still count as a normal day.
Your job: write the function long_days(miles, limit) so it returns a list of the day numbers whose miles are more than limit.
- Days are numbered from 1: the first item of
milesis day 1. - A day with exactly
limitmiles isn't a long day. - The day numbers are in order, and when no day is long, it returns an empty list,
[].
Worked through: in long_days([470, 540, 355, 330], 400), day 1 is 470 miles and day 2 is 540, both more than 400, while days 3 and 4 aren't. So it returns [1, 2].
Practiced live on the lesson page: write the Python right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
A loop over a list does the same job for every item, however many there are, and the built-in functions do the most common loops for you in one short call.