Loops, lists, and the patterns you'll use daily
Repeat work with for/while, store many values in lists, and build lists quickly with comprehensions.
Why this matters
Computers are good at one thing: doing the same thing over and over without getting bored. Loops let you repeat a block of code many times, and lists let you hold many values under one name. Together they unlock nearly every real program: process every row of a spreadsheet, ask every user a question, build up a collection of results, search through items to find one that matches. This lesson is the last warm-up you need before the existing course picks up the pace.
Learning objectives
After this lesson you will be able to:
- Create a list and read / change / add / remove items.
- Use a
forloop to visit every item in a list. - Build a new list with a comprehension.
- Use
range,enumerate, andzipto loop with index and pairing. - Loop with
whilewhen you do not know how many times in advance.
1. Lists β holding many values
A list holds an ordered collection of values, inside square brackets, separated by commas.
colors = ["red", "green", "blue"]
numbers = [1, 2, 3, 4, 5]
mixed = ["a", 1, True]
empty = []Reading items β counting from 0
colors[0] # 'red'
colors[1] # 'green'
colors[-1] # 'blue' (negative counts from the end)
len(colors) # 3 (how many items)Changing items
colors[0] = "purple"
print(colors) # ['purple', 'green', 'blue']Adding and removing
colors.append("yellow") # add to the end
colors.insert(0, "orange") # add at a position
colors.remove("green") # remove first matching item
last = colors.pop() # remove and return the last itemSlicing β a chunk of the list
colors[1:3] # items at index 1 and 2 (2 is not included)2. for loops β do something for each item
The for loop visits every item in a sequence.
colors = ["red", "green", "blue"]
for color in colors:
print(color)Prints:
red
green
blueRead it as: "for each color in colors, print it."
Looping over a string
A string is also a sequence of characters:
for ch in "hi":
print(ch) # h, then ifor over a list of numbers
total = 0
for n in [1, 2, 3, 4]:
total = total + n
print(total) # 10This "accumulate a running total" pattern is everywhere.
3. range β count without making a list
range(n) produces the numbers 0 to n-1 without creating a big list in memory.
for i in range(3):
print(i) # 0, 1, 2You can set start, stop, and step:
range(1, 4) # 1, 2, 3
range(0, 10, 2) # 0, 2, 4, 6, 8
range(5, 0, -1) # 5, 4, 3, 2, 14. enumerate β get the index too
Sometimes you want both the item and its position. enumerate gives you both.
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
print(index, color)Prints:
0 red
1 green
2 blueThe index, color in the loop unpacks the pair enumerate feeds you. This is your first taste of tuple unpacking (more later).
5. zip β loop over two lists side by side
zip pairs up items from two or more lists.
names = ["Ada", "Grace", "Linus"]
roles = ["engineer", "admiral", "hacker"]
for name, role in zip(names, roles):
print(f"{name} is a {role}")6. List comprehensions β build a list in one line
The most "Pythonic" pattern. Instead of:
squares = []
for n in range(5):
squares.append(n * n)
print(squares) # [0, 1, 4, 9, 16]You can write:
squares = [n * n for n in range(5)]
print(squares) # [0, 1, 4, 9, 16]Read it as: "make a list, where each item is n * n, for each n in range(5)."
You can add a condition:
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]Rule of thumb: if the comprehension fits comfortably on one line and reads clearly, use it. If it needs more than one line, use a regular for loop. Comprehensions are great; overstuffed ones are not.
7. while loops β repeat until something changes
A while loop repeats as long as its condition stays true.
count = 0
while count < 3:
print(count)
count = count + 1This prints 0, 1, 2 then stops when count reaches 3.
The danger: if the condition never becomes false, the loop runs forever. Make sure something inside the loop changes the condition. (If you ever do run an infinite loop, you can press Ctrl+C to interrupt it.)
8. break and continue
breakstops the loop immediately.continueskips to the next iteration.
for n in [1, 2, 3, 4, 5]:
if n == 3:
break # stop entirely at 3
print(n) # 1, 2for n in [1, 2, 3, 4, 5]:
if n == 3:
continue # skip 3, keep going
print(n) # 1, 2, 4, 5Common mistakes
- Off-by-one in
range.range(3)gives0,1,2, not1,2,3. If you want1,2,3userange(1, 4). - Forgetting to change the loop variable in
whileβ infinite loop. - Mutating a list while looping over it. Changing a list during a
forloop over that same list causes surprising results. Build a new list instead. - Confusing
appendwith overwriting.x = [1]; y = xtheny.append(2)also changesx, because both names point to the same list. (This is that "names vs references" idea from later β flag it, don't stress.) - Off-by-one in indexing.
colors[len(colors)]is an error β the last valid index islen(colors) - 1.
Hands-on lab (1 hour)
- Create a list of 5 numbers. Print the sum with a
forloop, then withsum(numbers). - Print each item in a list of names with its number using
enumerate. - Build a list of even numbers from 0 to 20 with a comprehension.
- Use
zipto print"A pairs with 1"style lines from two lists. - Write a
whileloop that counts down from 5 to 1 and prints "Liftoff!". - Challenge: given a list of words, make a new list of words longer than 4 characters, using a comprehension with an
if.
Self-check
- What does
range(4)produce? - What does a list comprehension
[x * 2 for x in range(3)]give? - What does
enumerateadd to a plainforloop? - When would you use
whileinstead offor? - What is the difference between
breakandcontinue?
References
Sign in to save your progress and earn badges.