Skip to content
  • Official
  • Beginner
  • English
  • 11 steps · 2 quizzes

Python Loops and Lists: Exercises for Beginners

Python loops exercises for beginners: lists, for, range and while, with a line-by-line visualiser and practice you check as you go.

  • Free
  • No account needed
  • Stop any time, pick up where you left off
Workshopy.io

WorkshopyOfficial

78 lessons · used by 2 teachers

For teachers

Teaching this? Run it live with your class.

  • Students join with a code — no accounts
  • See who’s done and who’s stuck, step by step
  • It’s your copy — change anything before class

Sign in to copy it to your workspace. It’s free.

Your path

11 steps · 2 quizzes · open any step, or read it here

  1. Start here: how do you get through a whole list?Start hereThese Python loops and lists exercises start with a problem you meet in any real file: a list of orders, sales or tickets that is far too long to add up or check by hand.InteractiveHands-on
    Read this step

    These Python loops and lists exercises start with a problem you meet in any real file: a list of orders, sales or tickets that is far too long to add up or check by hand. Writing one line per item doesn't work when the list has 500 items, or a different number every day.

    Interactive · A loop walks the list and builds the answer — try it in the lesson

    You just watched a for loop visit each order in turn while the total grew one block at a time. By the end of this lesson you'll write loops like that yourself, to add up, count and pick out the items you need.

    What you'll do

    • Store many values in one list, and change it with append, insert, remove, pop and sort
    • Repeat work with for loops, range() and while loops
    • Build totals, counts, the biggest item and new filtered lists with a loop
    • Spot the four loop mistakes beginners make most

    By the end you can

    • predict what a loop will print before you run it
    • add up, count and filter a list with a loop of your own
    • find and fix a loop that runs but gives the wrong answer

    You need print(), variables and if from your first programs, and any Python 3 for the short "Your turn" programs.

  2. Python loops and lists exercises: what you'll practiseIn this lesson you practise Python loops and lists with exercises: you keep many values in one list, then use for and while loops to go through them, add them up, count them and pick some out.InteractiveHands-on
    Read this step

    In this lesson you practise Python loops and lists with exercises: you keep many values in one list, then use for and while loops to go through them, add them up, count them and pick some out. A visualiser shows every line Python runs, so you can see what a loop does instead of guessing.

    Here is the whole idea in five lines. Watch the loop visit each sale in turn while total grows:

    Interactive · A loop adds up a week of sales — try it in the lesson

    Each step has something to play with and most have a short program to run in your own Python. Press Step to run one line at a time, Back to go back, Play to watch it run.

    Takeaway: a loop runs the same lines once for every item in a list.

  3. Lists: many values under one nameA list keeps many values, in order, under one name. You write it with square brackets and commasInteractiveHands-on
    Read this step

    A list keeps many values, in order, under one name. You write it with square brackets and commas:

    tickets = ["login", "refund", "bug", "access", "spam"]
    

    Each item has a position, its index. Python counts from 0, so the first item is tickets[0] and the fifth is tickets[4]. Negative indexes count back from the end: tickets[-1] is the last item, tickets[-2] the one before it. len(tickets) gives the number of items, here 5.

    Asking for an index that doesn't exist stops the program with an IndexError.

    Try it: move the slider, press Last, then press tickets[5]. Why is 5 out of range when the list has 5 items?

    Interactive · Indexes in a list — try it in the lesson

    Your turn

    tickets = ["login", "refund", "bug", "access", "spam"]
    print(len(tickets), tickets[0], tickets[-1])
    

    Check your work · Run the program above and paste what it printed. — check it in the lesson

    Takeaway: indexes start at 0, and -1 is the last item.

  4. Changing a list: append, insert, remove, pop, sortA list can change after you make it. You change it with methods: a dot after the list's name, then the method and brackets.InteractiveHands-on
    Read this step

    A list can change after you make it. You change it with methods: a dot after the list's name, then the method and brackets.

    Method What it does
    cart.append("eggs") adds an item at the end
    cart.insert(0, "tea") puts an item at index 0; the others move one place right
    cart.remove("milk") deletes the first item equal to "milk"; error if there is none
    cart.pop() takes the last item out and gives it back
    cart.sort() puts the items in order, in the same list

    append, insert, remove and sort change the list and give back nothing (None). Only pop gives back a value you can keep: last = cart.pop().

    Try it: press each method. Then type cake as the item and press remove(item), and press pop() until the list is empty.

    Interactive · List methods in a Python shell — try it in the lesson

    Your turn

    cart = ["milk", "bread"]
    cart.append("eggs")
    cart.insert(0, "tea")
    cart.remove("milk")
    last = cart.pop()
    print(cart, last)
    

    Check your work · Before you run it, write down what you expect. Then run it and paste what it printed. — check it in the lesson

    Takeaway: methods change the list in place; pop() also gives the item back.

  5. for loops: one pass for every itemA for loop runs the same lines once for every item in a listInteractiveHands-on
    Read this step

    A for loop runs the same lines once for every item in a list:

    for name in team:
        print("Hi", name)
    

    Read it as "for each name in team". On every pass Python puts the next item into the variable name and runs the indented lines under the for. When there are no items left, the loop ends and Python carries on with the first line that is not indented.

    • The line ends with a colon :.
    • The lines inside the loop are indented by four spaces. Indentation is how Python knows where the loop ends.
    • A loop works on a string too: it visits each letter.

    Try it: press Step and watch the purple loop mark move along the list. Count how many times line 3 runs. Then pick Letters of a word.

    Interactive · A for loop visits each item — try it in the lesson

    Your turn

    team = ["Ana", "Ben", "Chen"]
    for name in team:
        print(name, len(name))
    

    Check your work · Run it and paste what it printed. — check it in the lesson

    Takeaway: for runs the indented lines once per item, with the item in the loop variable.

  6. range(): loops that countSometimes you need numbers rather than items: do something 10 times, or number the lines of a report. range() gives a run of whole numbers for a loopInteractiveHands-on
    Read this step

    Sometimes you need numbers rather than items: do something 10 times, or number the lines of a report. range() gives a run of whole numbers for a loop:

    You write Numbers it gives
    range(5) 0, 1, 2, 3, 4
    range(1, 6) 1, 2, 3, 4, 5
    range(0, 15, 5) 0, 5, 10
    range(10, 0, -2) 10, 8, 6, 4, 2

    The three parts are start (included, 0 if you leave it out), stop (never included) and step (1 if you leave it out). Because the stop is never included, range(1, 6) is the way to count from 1 to 5.

    for day in range(1, 6):
        print("Day", day)
    

    list(range(...)) shows the numbers as a list, which is handy for checking.

    Try it: press the examples, then move the sliders. What happens with range(5, 1)? Set the step to 0.

    Interactive · range(start, stop, step) on a number line — try it in the lesson

    Your turn

    for n in range(2, 11, 3):
        print(n)
    

    Check your work · Run it and paste what it printed. — check it in the lesson

    Takeaway: range(start, stop, step) counts from start up to, but not including, stop.

  7. Check: lists, for and rangeFour questions on the first half.Quiz · 4 questions
    Read the questions

    Four questions on the first half.

    Question 1. tickets = ["a", "b", "c"]. What happens with print(tickets[3])?

    • It prints c
    • It prints a
    • IndexError: the indexes are 0 to 2
    • It prints nothing

    Question 2. Which method takes the last item out of a list and gives it back?

    • append()
    • remove()
    • pop()
    • sort()

    Question 3. How many times does the body of for i in range(4): run?

    • 3
    • 4
    • 5
    • It depends on i

    Question 4. What does this print: for letter in "hi": print(letter)

    • hi
    • h, then i on the next line
    • h i on one line
    • An error: you can only loop over a list
  8. Adding up, counting and finding the biggestMost work loops follow one pattern, the accumulator: a variable you set before the loop and update inside it.InteractiveHands-on
    Read this step

    Most work loops follow one pattern, the accumulator: a variable you set before the loop and update inside it.

    Goal Before the loop Inside the loop
    Total total = 0 total = total + amount
    Count big = 0 if amount > 100: then big = big + 1
    Biggest biggest = orders[0] if amount > biggest: then biggest = amount

    After the loop, the variable holds the answer. An average is the total divided by the count: total / len(orders).

    Try it: pick Total and press Play, then run Count and Biggest on the same orders. In Biggest, watch the line with if: the note under the picture shows the comparison Python makes, such as 135 > 40 is True.

    Interactive · The loop visits each order and updates the answer — try it in the lesson

    Why does Biggest start with orders[0] rather than 0? Think of a list where every number is negative.

    Your turn

    hours = [7.5, 8, 6, 9.5]
    total = 0
    for h in hours:
        total = total + h
    print(total, total / len(hours))
    

    Check your work · Run it and paste what it printed: the total hours and the average per day. — check it in the lesson

    Takeaway: set the answer before the loop, update it inside, read it after.

  9. Building a new list with a loopA loop can also make a new list: start with an empty list [], and append to it inside the loop. Keep some items (filter): append only when an if is true. Orders of 100 or more go into large. Change every item (transform): append a changed copy of each item.InteractiveHands-on
    Read this step

    A loop can also make a new list: start with an empty list [], and append to it inside the loop.

    • Keep some items (filter): append only when an if is true. Orders of 100 or more go into large.
    • Change every item (transform): append a changed copy of each item. Each name goes into tags in capitals with .upper().

    The original list stays as it was, so you can still use it.

    Try it: step through Keep some items and watch large grow only when the condition is True. Then run Change every item.

    Interactive · Filtering and changing items into a new list — try it in the lesson

    Your turn

    scores = [72, 95, 58, 88, 61]
    passed = []
    for s in scores:
        if s >= 70:
            passed.append(s)
    print(passed, len(passed))
    

    Check your work · Run it and paste what it printed. — check it in the lesson

    Takeaway: start with [], append inside the loop, and the original list is left as it was.

  10. while loops and break: repeat until something changesA for loop runs once per item. A while loop runs as long as a condition is True, and checks it again before every pass. Use it when you don't know in advance how many passes it takesInteractiveHands-on
    Read this step

    A for loop runs once per item. A while loop runs as long as a condition is True, and checks it again before every pass. Use it when you don't know in advance how many passes it takes:

    savings = 0
    months = 0
    while savings < 1000:
        savings = savings + 250
        months = months + 1
    

    Something inside the loop must change the condition, or it is True for ever and the program never ends (an infinite loop; press Ctrl+C to stop it).

    break leaves a loop at once, for or while. It is how you stop when you have found what you were looking for: the first wait over 10 minutes is escalated, and the rest are never checked.

    Try it: step through while: save to a goal. Look at the last check: why does 1000 < 1000 end the loop? Then run break: stop early and see which waits are never printed.

    Interactive · A while loop and a break — try it in the lesson

    Your turn

    tickets = 40
    days = 0
    while tickets > 0:
        tickets = tickets - 15
        days = days + 1
    print(days, tickets)
    

    Check your work · A support team closes 15 tickets a day. Run it and paste what it printed. — check it in the lesson

    Takeaway: while repeats while its condition is True; break leaves the loop at once.

Comments

You’ll sign in with Google before it’s posted.Comments are public — don’t name your students.
0 / 1,500

No comments yet. Be the first to say how it went.

Using it

Workshopy shares this lesson under CC BY 4.0. Anyone may use and change it, with credit to you. Anyone can learn it here, free. A copy in your workspace is yours to change and run live; your students never need an account.

Versions

  1. 2

    Version 2Current

    · A new Start here step with the lesson's scene; the cover is now a frame of the loop you step through in the lesson.

  2. 1

    Version 1

    · First published

Copies are made from the current version. A copy you already have doesn’t change.

More from Workshopy

All 78 lessons
All 13 Programming lessons