Python Tutorials

Choose a lesson to begin

Lists and For Loops

Lists let you store multiple items in a single variable. For loops let you process each item automatically. Together, they're one of Python's most powerful features!

What Is a List?

A list is a collection of items in square brackets [], separated by commas:

fruits = ["apple", "banana", "orange"]
numbers = [10, 20, 30, 40]
mixed = ["Vidar", 22, True, 3.14]

Creating Lists

# empty list
empty = []
# list of strings
colors = ["red", "green", "blue"]
# list of numbers
scores = [95, 87, 92, 100]
# list of mixed types (works, but avoid it)
stuff = ["text", 42, True]

Printing Lists

fruits = ["apple", "banana", "orange"]
print(fruits)
# output: ['apple', 'banana', 'orange']
# in an f-string
print(f"Fruits: {fruits}")
# output: Fruits: ['apple', 'banana', 'orange']

For Loops - The Basics

A for loop runs code for each item in a list:

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
orange

How it works:

  • Takes the first item ("apple") and stores it in fruit
  • Runs the indented code
  • Takes the next item ("banana") and repeats
  • Continues until all items are processed
  • Loop Syntax

    for item in list_name:
        # this code runs for each item
        print(item)

    Key parts:

    Variable Naming in Loops

    Use descriptive names:

    # good - clear what we're looping through
    for color in colors:
        print(color)
    for score in scores:
        print(score)
    # bad - unclear
    for x in colors:
        print(x)

    Using Loop Variables

    The loop variable (fruit, score, etc.) holds the current item:

    fruits = ["apple", "banana", "orange"]
    for fruit in fruits:
        print(f"I like {fruit}")

    Output:

    I like apple
    I like banana
    I like orange

    Loops with Numbers

    numbers = [10, 20, 30, 40, 50]
    for num in numbers:
        doubled = num * 2
        print(f"{num} doubled is {doubled}")

    Output:

    10 doubled is 20
    20 doubled is 40
    30 doubled is 60
    40 doubled is 80
    50 doubled is 100

    Accumulating Values

    Use a variable to build up a total:

    scores = [95, 87, 92, 88]
    total = 0
    for score in scores:
        total = total + score
    print(f"Total: {total}")
    # output: Total: 362

    How it works:

  • Start with total = 0
  • First loop: total = 0 + 95total = 95
  • Second loop: total = 95 + 87total = 182
  • Third loop: total = 182 + 92total = 274
  • Fourth loop: total = 274 + 88total = 362
  • Counting Items

    fruits = ["apple", "banana", "orange", "grape"]
    count = 0
    for fruit in fruits:
        count = count + 1
    print(f"We have {count} fruits")
    # output: We have 4 fruits

    Real-World Examples

    Process Shopping List

    shopping_list = ["milk", "bread", "eggs", "butter"]
    print("Shopping List:")
    for item in shopping_list:
        print(f"- {item.upper()}")

    Calculate Average Score

    scores = [85, 92, 78, 95, 88]
    total = 0
    for score in scores:
        total = total + score
    average = total / 5
    print(f"Average score: {average}")

    Format Names

    names = ["Vidar", "bob", "charli"]
    for name in names:
        formatted = name.upper()
        print(f"Hello, {formatted}!")

    Inventory Check

    products = ["laptop", "mouse", "keyboard", "monitor"]
    print("Inventory Check:")
    for product in products:
        print(f"✓ {product} - in stock")

    Indentation Is Critical!

    Correct:

    for num in [1, 2, 3]:
        print(num)      # indented - inside loop
        print("---")    # indented - inside loop
    print("Done!")      # not indented - runs once after loop

    Wrong:

    for num in [1, 2, 3]:
    print(num)  # eRROR! Must be indented

    Common Patterns

    Print each item:

    for item in items:
        print(item)

    Sum all numbers:

    total = 0
    for num in numbers:
        total = total + num

    Count items:

    count = 0
    for item in items:
        count = count + 1

    Transform each item:

    for name in names:
        upper_name = name.upper()
        print(upper_name)

    Try It Out!

  • Create a list of 5 numbers and print each one
  • Make a list of names and print "Hello, [name]!" for each
  • Create a list of prices and calculate the total
  • Make a list of words and count how many there are
  • Create a to-do list and print each item with a checkbox: "☐ Task"
  • Common Mistakes

    Forgetting the colon:

    # wrong
    for item in items
        print(item)
    # right
    for item in items:
        print(item)

    Forgetting to indent:

    # wrong
    for item in items:
    print(item)
    # right
    for item in items:
        print(item)

    Using the list name instead of the loop variable:

    # wrong
    for fruit in fruits:
        print(fruits)  # Prints the whole list each time!
    # right
    for fruit in fruits:
        print(fruit)   # Prints each fruit

    Next Steps

    You now know the fundamentals of Python! Practice these concepts, and you'll be ready to build real programs. Consider exploring:

    Keep coding! 🐍

    🐍 Python Runner