How to Write a For Loop in Python | The School of Code

Settings

Appearance

Choose a typography theme that suits your style

Back to How-to Guides
Python

How to Write a For Loop in Python

Learn how to use for loops in Python to iterate over sequences, ranges, and more.

PythonLoopsBasics

For loops in Python are used to iterate over sequences like lists, strings, and ranges.

Basic For Loop

Iterate over a list:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# cherry

Looping with range()

Generate a sequence of numbers:

# 0 to 4
for i in range(5):
    print(i)

# 1 to 5
for i in range(1, 6):
    print(i)

# 0 to 10, step by 2
for i in range(0, 11, 2):
    print(i)  # 0, 2, 4, 6, 8, 10

Loop with Index using enumerate()

Get both index and value:

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# Output:
# 0: apple
# 1: banana
# 2: cherry

Looping Over Dictionaries

Iterate over keys, values, or both:

person = {"name": "Alice", "age": 25, "city": "Paris"}

# Loop over keys
for key in person:
    print(key)

# Loop over values
for value in person.values():
    print(value)

# Loop over key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

Looping Over Multiple Lists with zip()

Iterate over multiple lists simultaneously:

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

Break and Continue

Control loop execution:

# Break - exit the loop early
for i in range(10):
    if i == 5:
        break
    print(i)  # 0, 1, 2, 3, 4

# Continue - skip to next iteration
for i in range(5):
    if i == 2:
        continue
    print(i)  # 0, 1, 3, 4

Summary

  • Use for item in sequence to iterate over any iterable
  • Use range() for numeric sequences
  • Use enumerate() when you need both index and value
  • Use zip() to iterate over multiple sequences together