runtime
31 / 250
lesson 31 Lists & Tuples · beginner

Make a list

A list holds many values in order under one name: a week of temperatures, a watchlist. A tuple holds a fixed record, such as a film's title and year.

You'll be able to
  • Write a list with square brackets and walk it with for
  • Count, total and test membership with len, a loop and in
  • Explain when a tuple fits better than a list, and why in on a list matches whole items only
The idea

A weather station reports a temperature every day. With one name per value (day1, day2 …) you couldn't loop over them, and a month of readings would need 31 names. A list keeps any number of values in order under one name: highs = [6.7, 7.2, 3.3]. Square brackets hold the items, and commas separate them.

Everything you did with the characters of a text works with the items of a list. for visits each item in order, len counts the items, and in asks whether a value is one of them.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · A week of daily highs
highs = [6.7, 7.2, 3.3, 7.2, 3.9, -2.1]
print(highs)
print(len(highs), "days")
warm = 0
for t in highs:
    if t > 5:
        warm = warm + 1
print(warm, "days above 5 C")
print(-2.1 in highs, 10 in highs)

A tuple is written with parentheses: ("Wild Archive", 2008, "de"). Use a tuple for a fixed record whose positions mean different things: a title, a year, a language. Use a list for a collection of similar things that may grow.

Watch what in means on each kind of value. On a text, in looks for a piece of the text. On a list, it looks for a whole item.

example-2.py · A watchlist and one film's record
watchlist = ["Glass Echo of Glass", "Wild Archive", "Glass Horizon on Fire"]
film = ("Wild Archive", 2008, "de")
print(film)
print(len(film))
print("Wild Archive" in watchlist)
print("Wild" in watchlist)
print("Wild" in "Wild Archive")

When to use it: use a list for many values of the same kind that you will loop over, count or search, such as readings, IDs or titles. Use a tuple for a small fixed record. Mistakes to avoid:

  • Expecting in on a list to find part of an item.
  • Forgetting the commas between items. ["a" "b"] is a list with one item, "ab".
Review
  • A list, written [a, b, c], holds values in order. for walks them, len counts them, and in matches whole items.
  • A tuple, written (a, b, c), is a fixed record such as a title and a year.
  • Check for an empty list before dividing by its length.
  • Next: pick items and pieces of a list by their position.

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Make a list — Lists & Tuples · Runtime