Lists & loops

A little repetition

Lesson 4 of 20 · 7 min · Module 2: Loops & functions

A list keeps values together. A for loop helps you work with each one without repeating yourself.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Create a list of related values
  • Trace a for loop
  • Keep a running total

The idea

Create a list with square brackets. Use for item in items: to visit each value. Python uses indentation to group the lines in a loop.

languages = ["Python", "JavaScript"]
for language in languages:
    print(language)

01A loop visits each value

for number in numbers assigns one list item at a time to number. The indented lines form the body. Lines after the indentation ends run after the loop.

for number in [1, 2, 3]:
    print(number)
Output
1
2
3

02Initialize before accumulating

Set total = 0 before the loop. Each total += number adds to the result already computed. Resetting total inside the loop would discard the earlier additions.

Your turn

Create numbers = [1, 2, 3, 4, 5]. Use a loop to calculate their sum in a variable named total, then print it.

What the checks look for

  • numbers contains all five values
  • total is 15
  • Prints the total
Try it in the editor →

Take this with you

A loop combines a collection, a repeated action, and a state that changes predictably.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →