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.

🌱 Module 0 7 min read Not started

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:

  1. Create a list and read / change / add / remove items.
  2. Use a for loop to visit every item in a list.
  3. Build a new list with a comprehension.
  4. Use range, enumerate, and zip to loop with index and pairing.
  5. Loop with while when 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.

python
colors = ["red", "green", "blue"]
numbers = [1, 2, 3, 4, 5]
mixed = ["a", 1, True]
empty = []

Reading items β€” counting from 0

python
colors[0]     # 'red'
colors[1]     # 'green'
colors[-1]    # 'blue'   (negative counts from the end)
len(colors)   # 3        (how many items)

Changing items

python
colors[0] = "purple"
print(colors)    # ['purple', 'green', 'blue']

Adding and removing

python
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 item

Slicing β€” a chunk of the list

python
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.

python
colors = ["red", "green", "blue"]

for color in colors:
    print(color)

Prints:

red
green
blue

Read it as: "for each color in colors, print it."

Looping over a string

A string is also a sequence of characters:

python
for ch in "hi":
    print(ch)     # h, then i

for over a list of numbers

python
total = 0
for n in [1, 2, 3, 4]:
    total = total + n
print(total)     # 10

This "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.

python
for i in range(3):
    print(i)     # 0, 1, 2

You can set start, stop, and step:

python
range(1, 4)       # 1, 2, 3
range(0, 10, 2)   # 0, 2, 4, 6, 8
range(5, 0, -1)   # 5, 4, 3, 2, 1

4. enumerate β€” get the index too

Sometimes you want both the item and its position. enumerate gives you both.

python
colors = ["red", "green", "blue"]

for index, color in enumerate(colors):
    print(index, color)

Prints:

0 red
1 green
2 blue

The 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.

python
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:

python
squares = []
for n in range(5):
    squares.append(n * n)
print(squares)    # [0, 1, 4, 9, 16]

You can write:

python
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:

python
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.

python
count = 0
while count < 3:
    print(count)
    count = count + 1

This 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

  • break stops the loop immediately.
  • continue skips to the next iteration.
python
for n in [1, 2, 3, 4, 5]:
    if n == 3:
        break          # stop entirely at 3
    print(n)           # 1, 2
python
for n in [1, 2, 3, 4, 5]:
    if n == 3:
        continue       # skip 3, keep going
    print(n)           # 1, 2, 4, 5

Common mistakes

  1. Off-by-one in range. range(3) gives 0,1,2, not 1,2,3. If you want 1,2,3 use range(1, 4).
  2. Forgetting to change the loop variable in while β†’ infinite loop.
  3. Mutating a list while looping over it. Changing a list during a for loop over that same list causes surprising results. Build a new list instead.
  4. Confusing append with overwriting. x = [1]; y = x then y.append(2) also changes x, because both names point to the same list. (This is that "names vs references" idea from later β€” flag it, don't stress.)
  5. Off-by-one in indexing. colors[len(colors)] is an error β€” the last valid index is len(colors) - 1.

Hands-on lab (1 hour)

  1. Create a list of 5 numbers. Print the sum with a for loop, then with sum(numbers).
  2. Print each item in a list of names with its number using enumerate.
  3. Build a list of even numbers from 0 to 20 with a comprehension.
  4. Use zip to print "A pairs with 1" style lines from two lists.
  5. Write a while loop that counts down from 5 to 1 and prints "Liftoff!".
  6. Challenge: given a list of words, make a new list of words longer than 4 characters, using a comprehension with an if.

Self-check

  1. What does range(4) produce?
  2. What does a list comprehension [x * 2 for x in range(3)] give?
  3. What does enumerate add to a plain for loop?
  4. When would you use while instead of for?
  5. What is the difference between break and continue?

References

Sign in to save your progress and earn badges.