Examples

Examples · Loops

Python Loop Examples

A runnable cookbook of everyday Python loop tasks — range, enumerate, while, reverse, zip, nested loops, break and comprehensions — each a short snippet you can run in the browser.

XCODXExamples · Updated

Overview

Short, copy-paste examples for the most common loop tasks in Python. Run any of them in the online Python compiler.

Examples

Count with range()

for n in range(5):
    print(n)          # 0 1 2 3 4

Index and value with enumerate()

letters = ["a", "b", "c"]
for i, letter in enumerate(letters):
    print(i, letter)  # 0 a, 1 b, 2 c

Repeat with a while loop

n = 3
while n > 0:
    print(n)          # 3 2 1
    n -= 1

Reverse a sequence

for x in reversed(["a", "b", "c"]):
    print(x)          # c b a

Loop two lists together with zip()

names = ["Ada", "Bo"]
ages = [36, 22]
for name, age in zip(names, ages):
    print(name, age)  # Ada 36, Bo 22

Nested loops over a grid

for row in range(2):
    for col in range(2):
        print(row, col)   # 0 0, 0 1, 1 0, 1 1

Stop early with break

for n in [1, 2, 3, 4]:
    if n == 3:
        break
    print(n)          # 1 2

Skip items with continue

for n in range(5):
    if n % 2 == 0:
        continue
    print(n)          # 1 3

Loop with an index and step

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

Build a list with a comprehension

squares = [n * n for n in range(1, 6)]
print(squares)        # [1, 4, 9, 16, 25]

Loop over a dictionary

prices = {"pen": 3, "pad": 6}
for item, price in prices.items():
    print(item, price)   # pen 3, pad 6

Frequently asked questions

How do I loop a set number of times in Python?
Use for n in range(5): — the body runs five times with n going 0 through 4.
How do I loop with the index in Python?
Use enumerate(): for i, item in enumerate(seq): gives the index and value together.
How do I loop two lists at once?
Use zip(): for a, b in zip(list1, list2): pairs items from both lists position by position.