Learn by reading through in order

for Loops with range / enumerate / zip

Get the Python for loop into your hands — iterate any collection and combine it with range, enumerate, and zip in your browser.

So far we've learned branching with if / elif and bulk checks with all() / any().

In this article, you'll pick up the for statement for running the same work across every element in a list. With if and for in your toolkit, you can write most practical day-to-day code.

Pulling out one element at a time with for

A for statement takes a repeatable object (an iterable) like a list, tuple, string, or dict, and pulls out elements one by one from the start, binding each to the variable you name and running your block each time.

The basic shape is one line of for variable in iterable: plus a 4-space-indented block.

What one iteration of for does
listpull oneelementassign tovariablerunblocknext elementrepeat

Pull one element from the collectionassign it to the variablerun the block → on to the next, repeating until elements run out.

# Loop over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)
# Output:
# apple
# banana
# orange

# Strings are iterable too (one character at a time)
for ch in "ABC":
    print(ch)
# Prints A / B / C in turn

Don't forget the colon and 4-space indent

The for line must end with : (a colon), and each line of the block must be indented by 4 spaces (or one tab). Mismatched indentation raises IndentationError.

Looping over a dict with for

If you pass a dict to for directly, only the keys are pulled out in turn. To get the values too, .items() is the usual choice. If you only need the values, use .values().

FormWhat you getTypical use
for key in d:keysWhen the key alone is enough
for value in d.values():valuesWhen you only need the values for aggregation
for key, value in d.items():key/value pairsWhen you need both — for formatted display or filtering
user = {"name": "alice", "age": 29, "role": "admin"}

# Keys only
for key in user:
    print(key)
# name / age / role

# Values only
for value in user.values():
    print(value)
# alice / 29 / admin

# Keys and values together
for key, value in user.items():
    print(f"{key}: {value}")
# name: alice / age: 29 / role: admin

Compute the total from a dict of products and unit prices.

① Define prices = {"apple": 180, "bread": 320, "milk": 250}.

② Initialize total = 0, then loop over .values() with for and add each value into total.

③ Print the total at the end with print(total).

(The explanation appears once you run the code correctly.)

Python Editor

Run code to see output

Repeating a fixed number of times with range()

range(n) is a built-in function that returns the integer sequence from 0 to n-1, and combined with for it's the go-to way to write fixed-count loops. There are 3 common ways to call it.

How range() works
range(5)0,1,2,3,45 iterationsproducesfor in turn
FormGenerated valuesUse
range(5)0, 1, 2, 3, 40 to n-1
range(2, 8)2, 3, 4, 5, 6, 7Specify start and end (end is exclusive)
range(1, 10, 2)1, 3, 5, 7, 9Specify start, end, and step
# Loop 0 to 4
for i in range(5):
    print(i)
# Prints 0 1 2 3 4 (5 lines)

# 2 to 7
for i in range(2, 8):
    print(i)

# 1 to 9 in steps of 2
for i in range(1, 10, 2):
    print(i)

# Use _ when you only need the count, not the value
for _ in range(3):
    print("retry...")

Naming the loop variable _ (an underscore) is a convention to immediately signal "this variable isn't used inside". i or j would still work, but reading code where they're never used makes a reader pause and ask why — so use _ when you only care about the count.

Compute the sum of integers from 1 to 10.

① Initialize total = 0.

② Use for and range() to add 1 through 10 to total.

③ Print the total with print(total).

Python Editor

Run code to see output

enumerate and zip for indices and parallel lists

In real-world code, you often want the position of each element as well, or you want to iterate over multiple lists in parallel. enumerate() and zip() make these much shorter and more readable.

enumerate() — looping with an index

Wrapping a list in enumerate(list) gives you (index, element) pairs in turn. It's handy for ranking displays or showing line numbers in error messages — anywhere you want to attach "which one" to each value.

products = ["apple", "bread", "milk"]

for index, name in enumerate(products):
    print(f"{index}: {name}")
# 0: apple
# 1: bread
# 2: milk

# To start at 1, pass the start as the second argument
for rank, name in enumerate(products, 1):
    print(f"#{rank}: {name}")
# #1: apple / #2: bread / #3: milk

zip() — iterating multiple lists in parallel

zip(list1, list2, ...) lets you pull elements at the same index together from multiple lists. It stops when the shortest list runs out, so it's safe even with mismatched lengths.

names  = ["Alice", "Bob", "Carol"]
scores = [82, 91, 65]

for name, score in zip(names, scores):
    print(f"{name}: {score} pts")
# Alice: 82 pts / Bob: 91 pts / Carol: 65 pts

Build a numbered price list from product names and prices.

① Define items = ["apple", "bread", "milk"] and prices = [180, 320, 250].

② Combining enumerate and zip, print 1-based numbers, names, and prices in the format 1. apple : $1.80.

Python Editor

Run code to see output

Controlling loops with break and continue

It's common to want to stop because you found what you needed or skip just this iteration. The first uses break to leave the loop immediately; the second uses continue to skip the rest of this iteration and move to the next element.

break vs. continue
for loopif condbreakout of loopfor loopif condcontinuenext elementTrueexitTrueskip

break ends the loop itself, so the remaining elements aren't evaluated at all. continue only skips the rest of this iteration and moves on to the next element — the loop as a whole keeps going. Both are typically called from inside an if.

# break: stop as soon as we find the target
users = ["alice", "bob", "carol", "dave"]
for name in users:
    if name == "carol":
        print("Found it")
        break
    print(f"checking: {name}")
# checking: alice / checking: bob / Found it

# continue: skip 0s when summing
scores = [80, 0, 65, 0, 91]
total = 0
for score in scores:
    if score == 0:
        continue
    total += score
print(total)   # 80 + 65 + 91 = 236

Walk through a stock list, using continue to skip and using break when you spot something abnormal.

① Define stock = [12, 4, 0, 9, -1, 3].

② Use enumerate to pull out 1-based numbers and quantities, and:

 - For items with quantity 0, skip without printing (continue).

 - For an item with a negative quantity, print "Abnormal value detected at #X" and break.

 - Otherwise, print "#X OK (Y units)".

Python Editor

Run code to see output

In this article, we covered the big picture of for: iterating over lists and dicts, counting with range(), extending with enumerate() / zip(), and controlling flow with break / continue.

In the next article, we'll look at the while loop — used for repeating when you don't know the count up front — and how to avoid infinite loops.

QUIZ

Knowledge Check

Answer each question one by one.

Q1What does this code print?
for i in range(2, 6):
print(i)

Q2When you expand enumerate(['a', 'b', 'c'], 1) with for, what pairs are produced?

Q3What does this code print?
nums = [1, 2, 3, 4, 5]
for n in nums:
if n == 3:
continue
print(n)