Real data comes in groups: a list of prices, a list of names, the rows of a file. Python holds a group of values in a list, and it repeats work for each value with a loop. These two ideas let a short program deal with ten values or ten million in the same way.
Lists
A list is written with square brackets and commas: prices = [120, 80, 650, 45]. Each value has a position called an index, which starts at 0, not 1. So prices[0] is the first value and prices[-1] is the last. A list can hold any values, and the list can grow and shrink.
len(prices)counts the items.sum,maxandminwork on lists of numbers.prices.append(300)adds to the end.prices.insert(0, 10)adds at a position.prices.remove(80)removes the first value that equals 80.prices.pop()removes and returns the last one.sorted(prices)returns a new sorted list.prices.sort()sorts the list itself.prices[1:3]is a slice: the items from index 1 up to, but not including, index 3.prices[:2]is the first two, andprices[2:]is everything from index 2 on.x in pricestells you whether a value is in the list.
The for loop
A for loop runs the indented block once for each item. Read this program and its output. It also shows enumerate, which gives you a counter together with each item, range, which makes a series of numbers, a while loop, and a list comprehension.
prices = [120, 80, 650, 45]
print(len(prices), prices[0], prices[-1])
prices.append(300)
print(sum(prices), max(prices), min(prices))
for price in prices:
if price > 500:
print("Expensive:", price)
for i, price in enumerate(prices, start=1):
print(i, price)
for n in range(3):
print("Round", n)
total = 0
count = 0
while total < 500:
total += prices[count]
count += 1
print("Reached", total, "after", count, "items")
cheap = [p for p in prices if p < 100]
doubled = [p * 2 for p in prices]
print(cheap)
print(doubled)
print(sorted(prices))
print(prices[1:3])
4 120 45
1195 650 45
Expensive: 650
1 120
2 80
3 650
4 45
5 300
Round 0
Round 1
Round 2
Reached 850 after 3 items
[80, 45]
[240, 160, 1300, 90, 600]
[45, 80, 120, 300, 650]
[80, 650]
for price in prices:takes each value in turn and calls itprice. The name is yours to choose. Make it singular, to read like English.enumerate(prices, start=1)gives pairs like(1, 120), so you can number the lines starting from 1.range(3)gives 0, 1, 2. It stops before the number you give.range(1, 6)gives 1 to 5.- A
whileloop repeats as long as its condition is true. In the example, it adds prices until the total reaches 500. If the condition never becomes false, you get an endless loop. Press Ctrl+C to stop it. - A list comprehension builds a new list in one line:
[p for p in prices if p < 100]reads as *p for each p in prices, if p is below 100*. It is a short form of a loop that makes a list.
break and continue
Two small commands change how a loop runs. break ends the loop at once. continue skips the rest of this round and goes to the next. For example, a search loop can break as soon as it finds what it wants, so it does not do needless work.
names = ["Asha", "Ravi", "Meena", "Dev"]
for name in names:
if name == "Meena":
print("Found Meena")
break
print("Checked", name)
This prints Checked Asha, Checked Ravi and Found Meena. It never looks at Dev.
Changing a list while you loop over it
Do not add or remove items from a list while you loop over the same list. The loop can skip items or behave oddly. Build a new list instead, as the list comprehension does, or loop over a copy such as for p in prices[:]:.
Copying lists
b = a does not make a copy of a list. Both names point to the same list, so a change through one shows in the other. Make a real copy with b = a.copy() or b = a[:]. This surprises many beginners, and it is worth remembering.
Choosing between for and while
- Use
forwhen you know what to loop over: a list, a range, the lines of a file. - Use
whilewhen you repeat until something happens, such as the user typing the right answer. - If you can write it with
for, it is usually the clearer choice.
Your task
- Make a list of five test scores. Print the total, the average, the highest, and how many scores are above the average.
- Use a
forloop withenumerateto print1. Asha 90style lines for a list of names and a list of scores (use two lists and the index). - Write a
whileloop that keeps asking for a number until the user types0, and then prints the sum of what they typed. - Use a list comprehension to build a list of the squares of the numbers 1 to 10.
How to check it worked
- The average for scores
[72, 85, 90, 66, 85]is79.6, and3scores are above it. - Your
whileloop stops when you type 0 and shows the right sum. - You can explain why
range(3)stops at 2.