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.
- Write a list with square brackets and walk it with
for - Count, total and test membership with
len, a loop andin - Explain when a tuple fits better than a list, and why
inon a list matches whole items only
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.
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.
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
inon a list to find part of an item. - Forgetting the commas between items.
["a" "b"]is a list with one item,"ab".
- A list, written
[a, b, c], holds values in order.forwalks them,lencounts them, andinmatches 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.