small steps

Work with lists, dictionaries and for loops in Python

Keep a week of step counts in a list and a dictionary, then loop over them to find the total, the average, your best day and the days you hit your goal.

BasicsBy Noufal18 min readPublished Tested on Python 3.15
Part 2 of 4 in Python basics
6 steps in this tutorial
  1. See the problem
  2. Keep the week in a list
  3. Loop over the list
  4. Change the list
  5. Name the days with a dictionary
  6. Start a new week

What you'll learn

  • Keep many values in one list, and add to, sort and slice it
  • Loop over a list to count and collect the values you want
  • Look values up by name with a dictionary
  • Copy a list or dictionary without changing the original

Before you start

Your phone counts your steps every day, and a week is already seven numbers. One variable per number works for a day or two, then falls apart. In six small steps, you'll keep a week of step counts in a list and a dictionary, and loop over them to find the total, the average, your best day and the days you reached your goal.

Step 1: See the problem

Here's a week of step counts, one variable per day:

week_vars.py
mon = 6200
tue = 8400
wed = 4100
thu = 9700
fri = 7300
sat = 11200
sun = 5600

total = mon + tue + wed + thu + fri + sat + sun
print("Total:", total)
print("Average:", total / 7)
Total: 52500
Average: 7500.0

That works. Now you want to know which days reached a goal of 8,000 steps. With one variable per day, that's one if per day:

Python
if mon >= 8000:
    print("mon")
if tue >= 8000:
    print("tue")
# ... and five more, one for each day left

Seven names, seven ifs, and the same line typed again for every day. Next week brings seven more names, and a month brings thirty. The 7 in the average is typed by hand too, so it's wrong the moment a day is missing.

What you want is one name for the whole week, and a way to say "for each day, do this" once. That's a list and a for loop.

Step 2: Keep the week in a list

A list holds many values, in order, under one name. Write the values inside square brackets, separated by commas:

week.py
steps = [6200, 8400, 4100, 9700, 7300, 11200, 5600]

print("Days:", len(steps))
print("Total:", sum(steps))
print("Average:", sum(steps) / len(steps))
print("Best:", max(steps))
print("Worst:", min(steps))
Days: 7
Total: 52500
Average: 7500.0
Best: 11200
Worst: 4100

len counts the values, sum adds them up, and max and min find the biggest and the smallest. Nothing in this code says 7 any more: put an eighth day in the list, and every line still gives the right answer. (Dividing with / always gives a decimal number, which is why the average is 7500.0.)

Each value has a position in the list, called its index. You get one value by putting its index in square brackets:

Python shell
>>> steps = [6200, 8400, 4100, 9700, 7300, 11200, 5600]
>>> steps[0]
6200
>>> steps[1]
8400
>>> steps[-1]
5600

Indexes count from 0, so steps[0] is Monday and steps[1] is Tuesday. A negative index counts from the end: steps[-1] is always the last day, however long the list gets.

Watch out

A week's indexes run from 0 to 6, not 1 to 7. steps[7] asks for an eighth day that isn't there, and Python stops with IndexError: list index out of range. Sunday is steps[6], or steps[-1].

Try it

Before you run them, work out what steps[2] and steps[-2] give. Then check in the Python shell. Which days are they?

Now you have the whole week under one name, and Python can count, add and compare it for you. In Step 3, you'll go through it one day at a time.

Step 3: Loop over the list

A for loop runs the same lines once for each value in a list. Here it counts the days that reached the goal:

goal.py
steps = [6200, 8400, 4100, 9700, 7300, 11200, 5600]
goal = 8000

good_days = 0
for count in steps:
    if count >= goal:
        good_days += 1

print("Days at the goal:", good_days)
Days at the goal: 3

Here's how it works:

  • for count in steps: takes the first value, 6200, puts it in count and runs the indented lines. Then it does the same with 8400, and so on, seven times in all. count is a name you choose; for day_steps in steps: would work the same.
  • The indented lines are the loop's body. The if inside it runs once for each day.
  • good_days += 1 adds one to good_days. It's short for good_days = good_days + 1.
  • The last print isn't indented, so it runs once, after the loop has finished.

Counting tells you how many days reached the goal. To see which counts they were, collect them in a new list:

Python
good = []
for count in steps:
    if count >= goal:
        good.append(count)

print(good)
[8400, 9700, 11200]

[] is an empty list, and append adds a value to its end. Starting empty and appending inside a loop is one of the most common patterns in Python.

Try it

Change goal to 7000 and run both loops again. How many days reach it now, and which counts are they?

Now you can go through a list and pick out what you need, however long it is. In Step 4, you'll change the list itself.

Step 4: Change the list

A list isn't fixed: you can add to it, sort it and take part of it. Here's the next Monday added on, and three ways to look at the result:

recent.py
steps = [6200, 8400, 4100, 9700, 7300, 11200, 5600]
steps.append(8800)  # next Monday

print("Days so far:", len(steps))
print("Last 3 days:", steps[-3:])
print("Smallest first:", sorted(steps))
print("Still in day order:", steps)
Days so far: 8
Last 3 days: [11200, 5600, 8800]
Smallest first: [4100, 5600, 6200, 7300, 8400, 8800, 9700, 11200]
Still in day order: [6200, 8400, 4100, 9700, 7300, 11200, 5600, 8800]

Here's what each part does:

  • steps.append(8800) changes the list itself: it has eight values now.
  • steps[-3:] is a slice, a new list made from part of the old one. Before the colon is where it starts (-3, three from the end), and after it is where it stops; left empty, it goes to the end. steps[:3] would give the first three days.
  • sorted(steps) gives you a new list, sorted from smallest to biggest, and leaves steps as it was. That matters here: in day order, a count's position still tells you which day it was.

Lists also have a sort method, steps.sort(), which sorts the list itself, in place, instead of making a new one.

Watch out

steps.sort() changes the list and gives back nothing, which Python writes as None. So steps = steps.sort() sorts the week, then replaces it with None: print(steps) prints None, and sum(steps) stops with TypeError: 'NoneType' object is not iterable. Write steps.sort() on a line of its own, or use sorted(steps) when you want a new list.

Try it

How would you get the three best days, biggest first? sorted(steps, reverse=True) sorts from biggest to smallest; add a slice to keep the first three.

Now you can grow a list, sort it and take the part you need. But a list only knows positions: to know that 11200 was Saturday, you have to remember that Saturday is index 5. In Step 5, the days get their names.

Step 5: Name the days with a dictionary

A dictionary stores each value under a name you choose, called its key. Write each pair as key: value inside curly braces:

days.py
week = {
    "Mon": 6200,
    "Tue": 8400,
    "Wed": 4100,
    "Thu": 9700,
    "Fri": 7300,
    "Sat": 11200,
    "Sun": 5600,
}

print("Saturday:", week["Sat"])

for day, count in week.items():
    if count >= 8000:
        print(day, count)
Saturday: 11200
Tue 8400
Thu 9700
Sat 11200

Here's how it works:

  • week["Sat"] looks up the value stored under the key "Sat". Square brackets again, but with a key instead of a position.
  • week.items() gives you each key with its value, in pairs, in the order you wrote them. for day, count in puts the two parts of each pair into two names, so the loop knows both the day and its count.
  • To change a value, or add a new one, assign to its key: week["Sun"] = 6400.

A loop straight over a dictionary, for day in week:, gives you the keys. That's enough to find the best day, because each key leads to its count:

Python
best_day = "Mon"
for day in week:
    if week[day] > week[best_day]:
        best_day = day

print("Best day:", best_day)
Best day: Sat

The loop starts by taking Monday as the best day so far, then compares every day with it, and keeps whichever is bigger.

Watch out

Keys have to match exactly, capitals included. week["sat"] stops with KeyError: 'sat'. When a key might not be there, use get: week.get("sat") gives None instead of an error, and week.get("sat", 0) gives 0.

Try it

Add week["Sun"] = 9000 before the loop in days.py and run it again. Which days reach the goal now?

Now you can look a value up by its name and loop over names and values together. In Step 6, you'll plan next week, and meet the trap that catches almost everyone once.

Step 6: Start a new week

For next week, you want a plan: this week's counts, with every day below the goal raised to 8,000. A natural first try is to make the plan from this week and change it:

plan.py
week = {
    "Mon": 6200, "Tue": 8400, "Wed": 4100, "Thu": 9700,
    "Fri": 7300, "Sat": 11200, "Sun": 5600,
}

plan = week
for day in plan:
    if plan[day] < 8000:
        plan[day] = 8000

print("This week:", week)
print("Plan:", plan)
This week: {'Mon': 8000, 'Tue': 8400, 'Wed': 8000, 'Thu': 9700, 'Fri': 8000, 'Sat': 11200, 'Sun': 8000}
Plan: {'Mon': 8000, 'Tue': 8400, 'Wed': 8000, 'Thu': 9700, 'Fri': 8000, 'Sat': 11200, 'Sun': 8000}

The plan is right, but this week's real counts are gone: Monday says 8000, not 6200. plan = week didn't copy anything. It gave the same dictionary a second name, so week and plan are two names for one dictionary, and a change made through one shows through the other.

To get a separate dictionary, ask for a copy:

plan.py
week = {
    "Mon": 6200, "Tue": 8400, "Wed": 4100, "Thu": 9700,
    "Fri": 7300, "Sat": 11200, "Sun": 5600,
}

plan = week.copy()
for day in plan:
    if plan[day] < 8000:
        plan[day] = 8000

print("This week:", week)
print("Plan:", plan)
This week: {'Mon': 6200, 'Tue': 8400, 'Wed': 4100, 'Thu': 9700, 'Fri': 7300, 'Sat': 11200, 'Sun': 5600}
Plan: {'Mon': 8000, 'Tue': 8400, 'Wed': 8000, 'Thu': 9700, 'Fri': 8000, 'Sat': 11200, 'Sun': 8000}

Now plan is a dictionary of its own, and this week's counts stay as they were.

Watch out

= never copies a list or a dictionary: it gives the same one another name. Change it through either name, and both names see the change. When you want a separate one to change, make it with .copy(), which works the same on lists: next_week = steps.copy().

Try it

Use week and plan to work out how many extra steps next week's plan asks for: for each day, the plan's count minus the real one, all added up.

Now you can keep a week of numbers in a list or a dictionary, loop over it to count, collect and compare, and copy it safely before you change it. The same few tools work for marks, prices, scores or anything else that comes in a pile.

Recap

  • A list keeps values in order: steps[0] is the first, steps[-1] the last, and len, sum, max and min work on the whole list.
  • for count in steps: runs the indented lines once for each value. Count with a variable, or collect values in a new list with append.
  • sorted(steps) gives a new sorted list. steps.sort() sorts the list itself and gives back None.
  • A dictionary looks values up by key: week["Sat"], or week.get("Sat", 0) when the key might be missing. Loop over week.items() to get each key with its value.
  • = gives a list or dictionary a second name. .copy() makes a separate one.

Check yourself

Five quick questions.

In steps = [6200, 8400, 4100, 9700, 7300, 11200, 5600], which gives Sunday's count, the last one?
Show the answer

steps[-1]: A negative index counts from the end, so steps[-1] is the last value, however long the list. steps[6] works too.

In goal.py, you indent the last line, print("Days at the goal:", good_days), so it sits inside the for loop. What happens?
Show the answer

It prints the count so far after every day: seven lines: Indented lines are the loop's body and run once for each value. Left unindented, the print runs once, after the loop.

What does print(steps) show after steps = steps.sort()?
Show the answer

None: sort() sorts the list in place and gives back None, and = puts that in steps. Write steps.sort() alone, or use sorted(steps).

In the tutorial's week dictionary, with keys from "Mon" to "Sun", what does week["sat"] do?
Show the answer

Stops with a KeyError: Keys have to match exactly, capitals included, and there's no "sat". week.get("sat", 0) would give 0 instead.

You write plan = week, then plan["Mon"] = 8000. What is week["Mon"] now?
Show the answer

8000: plan = week doesn't copy: both names lead to one dictionary, so the change shows through both. Use plan = week.copy().