Skip to content

Module 6 · Loops and Iteration — topic 3 of 12

for loops

A for loop runs its body once for each item in a sequence or other iterable. Learn to loop over lists, strings, tuples and dictionaries, with enumerate() and zip() for indexes and pairs.

Beginner 12 min read·Lesson 72 of 306 in Python Programming

Learning objectives

  • Loop over lists, strings, tuples and dictionaries
  • Get index and item together with enumerate()
  • Loop over two sequences in parallel with zip()

Definition

A for loop runs its body once for each item in a sequence or other iterable. Learn to loop over lists, strings, tuples and dictionaries, with enumerate() and zip() for indexes and pairs.

Introduction

A for loop takes each item of a collection in turn, assigns it to a loop variable, and runs the body. When there are no items left, the loop ends. You don’t manage a counter or a stopping condition yourself.

Why it matters

Processing every item of a collection is the most common kind of repetition: every student, every line in a file, every character in a string. for expresses it directly and can’t accidentally run forever.

Detailed explanation

for name in iterable: works with any iterable: lists, tuples, strings, sets, dictionaries, ranges, files and more.

The loop variable is an ordinary variable. It is rebound to the next item at the start of each iteration and keeps the last value after the loop.

Strings are iterated character by character. Dictionaries are iterated by key; use .items() for key–value pairs and .values() for values.

enumerate(items, start=1) gives the position and the item together, avoiding manual counters.

zip(a, b) pairs items from two or more iterables and stops at the shortest.

Don’t add or remove items from a list while looping over it; loop over a copy or build a new list instead.

Changing the loop variable inside the body doesn’t affect the next iteration: in for n in range(5): n = 100, the next pass still receives the next number from range. To change which items are processed, change the iterable before the loop or use a while loop.

Syntax

Text
for item in items:
use(item)
for index, item in enumerate(items, start=1):
use(index, item)
  • The loop variable takes each item in turn.
  • enumerate adds a counter.
  • The body repeats once per item.

Code examples

Lists and strings

Python
for city in ["Delhi", "Pune", "Goa"]:
print(city.upper())
for letter in "abc":
print(letter * 2)
Output
DELHI
PUNE
GOA
aa
bb
cc

Dictionaries

Python
prices = {"tea": 20, "coffee": 35}
for item, price in prices.items():
print(item, "costs", price)
Output
tea costs 20
coffee costs 35

More examples

Numbered results with enumerate and zip

Python
names = ["Asha", "Ben", "Chen"]
scores = [88, 72, 95]
for rank, (name, score) in enumerate(sorted(zip(names, scores), key=lambda p: p[1], reverse=True), start=1):
print(f"{rank}. {name:<5} {score}")
longest = ""
for name in names:
if len(name) > len(longest):
longest = name
print("Longest name:", longest)
Output
1. Chen  95
2. Asha  88
3. Ben   72
Longest name: Asha

Step-by-step explanation

  • zip pairs each name with its score: ("Asha", 88) and so on.
  • sorted orders the pairs by score, highest first.
  • enumerate(..., start=1) numbers them from 1, and (name, score) unpacks each pair.
  • The second loop keeps the longest name seen so far; Asha wins because Chen has the same length but comes later.

Expected output

Running “Numbered results with enumerate and zip” prints exactly:

TextOutput
1. Chen 95
2. Asha 88
3. Ben 72
Longest name: Asha

Practical applications

  • Reports loop over database rows to print each record.
  • Email tools loop over a recipient list to send messages.
  • Data scripts zip columns together to build records.

Best practices

  • Loop directly over items rather than over indexes.
  • Use enumerate for positions and zip for parallel lists.
  • Give the loop variable a singular name of the collection: for student in students.

Common mistakes

Manual index counting

Avoid

i = 0
for name in names:
print(i, name)
i += 1

Prefer

for i, name in enumerate(names):
print(i, name)

enumerate is clearer and can’t forget to update the counter.

Removing items while looping

Avoid

for x in nums:
if x < 0:
nums.remove(x)

Prefer

nums = [x for x in nums if x >= 0]

Changing the list during iteration skips items.

Key takeaways

  • for runs once per item of an iterable.
  • Use .items() to loop over dictionary pairs.
  • enumerate() adds positions; zip() pairs sequences.

Try it yourself

  1. 1
    Print each word of a sentence with its position, starting from 1.
  2. 2
    Loop over two lists of items and quantities with zip and print each pair.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic