Lesson 16: for Loops (Iterating Through Lists)
Learn how to write for loops, use iteration variables, process items, build lists, count values, and combine loops with conditionals in Python.
Introduction
You've learned how to store multiple items in lists. You've learned how to make decisions with if statements.
But so far, to work with every item in a list, you'd need to write code for each one individually:
rooms = ["Office 1", "Office 2", "Office 3", "Office 4", "Office 5"]
print(rooms[0])
print(rooms[1])
print(rooms[2])
print(rooms[3])
print(rooms[4])
This is manageable for 5 rooms. It's absurd for 500.
for loops solve this. They let you write code once and apply it to every item in a list automatically.
This is the lesson where Python stops being a learning exercise and starts being genuinely useful.
Lesson Overview
This section contains a general overview of topics you will learn in this lesson.
- Writing basic for loops
- Loop variables and iteration
- Processing each item
- Building new lists while looping
- Counting and accumulating values
- Combining loops with conditionals
Basic for Loop
A for loop processes each item in a list, one at a time.
rooms = ["Office 1", "Office 2", "Office 3"]
for room in rooms:
print(room)
Output:
Office 1
Office 2
Office 3
The code inside the loop (the indented part) runs once for each item in the list.
The Syntax
for item in list:
# code block (indented)
# this runs once for each item
Key parts:
for— keyword that starts the loopitem— temporary variable that holds the current itemin— keyword connecting the variable to the listlist— the list you're looping through:— colon required- Indented block — code that runs for each item
How It Works
Python processes the loop step by step:
sheets = ["A-101", "A-102", "A-201"]
for sheet in sheets:
print(f"Processing {sheet}")
Step 1: sheet = "A-101", print "Processing A-101" Step 2: sheet = "A-102", print "Processing A-102" Step 3: sheet = "A-201", print "Processing A-201" Done: Loop exits, code continues
The loop variable (sheet) automatically updates with each iteration.
Naming Loop Variables
The loop variable name is up to you. Choose something descriptive.
# Good - descriptive
for room in rooms:
print(room)
for sheet_number in sheet_numbers:
print(sheet_number)
for area in room_areas:
print(area)
# Bad - vague
for x in rooms:
print(x)
for item in room_areas:
print(item)
The name should make the code readable. Someone should be able to understand what's being processed.
Processing Each Item
You can do anything with the current item inside the loop.
Check conditions:
room_areas = [450.5, 380.2, 520.8, 410.3]
for area in room_areas:
if area < 400:
print(f"Warning: Room area {area}m² is below minimum")
Output:
Warning: Room area 380.2m² is below minimum
Perform calculations:
room_areas = [450.5, 380.2, 520.8, 410.3]
for area in room_areas:
area_sqft = area * 10.764
print(f"{area}m² = {area_sqft:.1f} sq ft")
Architectural Example: Validating Rooms
room_areas = [450.5, 380.2, 520.8, 410.3, 395.7]
minimum_area = 400
print("Room Compliance Check:")
print("-" * 30)
for area in room_areas:
if area >= minimum_area:
status = "✓ Compliant"
else:
status = "✗ Non-compliant"
print(f"{area}m²: {status}")
Output:
Room Compliance Check:
------------------------------
450.5m²: ✓ Compliant
380.2m²: ✗ Non-compliant
520.8m²: ✓ Compliant
410.3m²: ✓ Compliant
395.7m²: ✗ Non-compliant
You wrote the logic once. It checked all 5 rooms. It would work the same for 500 rooms.
Building New Lists
You can create a new list by appending items during the loop.
Filter large rooms:
room_areas = [450.5, 380.2, 520.8, 410.3, 395.7]
large_rooms = []
for area in room_areas:
if area >= 500:
large_rooms.append(area)
print(large_rooms)
# Output: [520.8]
Transform data:
areas_sqm = [450.5, 380.2, 520.8]
areas_sqft = []
for area in areas_sqm:
area_sqft = area * 10.764
areas_sqft.append(area_sqft)
print(areas_sqft)
# Output: [4849.122, 4092.4528, 5605.8752]
Counting and Accumulating
Use loops to count items or calculate totals.
Count compliant rooms:
room_areas = [450.5, 380.2, 520.8, 410.3, 395.7]
compliant_count = 0
for area in room_areas:
if area >= 400:
compliant_count += 1
print(f"Compliant rooms: {compliant_count} out of {len(room_areas)}")
# Output: Compliant rooms: 3 out of 5
Calculate total area:
room_areas = [450.5, 380.2, 520.8, 410.3, 395.7]
total_area = 0
for area in room_areas:
total_area += area
average_area = total_area / len(room_areas)
print(f"Total area: {total_area}m²")
print(f"Average area: {average_area:.1f}m²")
# Output:
# Total area: 2157.5m²
# Average area: 431.5m²
Looping Through Different Types
Numbers:
floor_numbers = [1, 2, 3, 4, 5]
for floor in floor_numbers:
print(f"Processing floor {floor}")
Strings:
sheet_numbers = ["A-101", "A-102", "A-201"]
for sheet in sheet_numbers:
print(f"Sheet: {sheet}")
Mixed (but keep lists homogeneous when possible):
# Works, but not recommended
mixed = ["A-101", 12, True]
for item in mixed:
print(item)
Real Architectural Workflows
Example 1: Sheet Status Report
sheets = ["A-101", "A-102", "A-201", "A-202", "S-101"]
issued = ["A-101", "A-201", "S-101"]
print("Sheet Status Report:")
print("-" * 40)
for sheet in sheets:
if sheet in issued:
status = "Issued"
else:
status = "Draft"
print(f"{sheet}: {status}")
Output:
Sheet Status Report:
----------------------------------------
A-101: Issued
A-102: Draft
A-201: Issued
A-202: Draft
S-101: Issued
Example 2: Room Categorization
room_areas = [450.5, 380.2, 520.8, 410.3, 395.7, 680.4]
small = []
standard = []
large = []
for area in room_areas:
if area < 400:
small.append(area)
elif area < 600:
standard.append(area)
else:
large.append(area)
print(f"Small rooms: {len(small)}")
print(f"Standard rooms: {len(standard)}")
print(f"Large rooms: {len(large)}")
# Output:
# Small rooms: 2
# Standard rooms: 3
# Large rooms: 1
Example 3: Building File Names
sheet_numbers = ["A-101", "A-102", "A-201"]
project_code = "2024-001"
file_names = []
for sheet in sheet_numbers:
file_name = f"{project_code}_{sheet}_Floor_Plan.pdf"
file_names.append(file_name)
for file_name in file_names:
print(file_name)
# Output:
# 2024-001_A-101_Floor_Plan.pdf
# 2024-001_A-102_Floor_Plan.pdf
# 2024-001_A-201_Floor_Plan.pdf
The range() Function
Sometimes you need to loop a specific number of times, not through a list.
for i in range(5):
print(i)
Output:
0
1
2
3
4
range(5) creates a sequence from 0 to 4 (5 numbers total).
Architectural example:
for floor in range(1, 11):
print(f"Processing floor {floor}")
# Output:
# Processing floor 1
# Processing floor 2
# ...
# Processing floor 10
range(1, 11) creates numbers from 1 to 10 (11 is exclusive).
Looping with Indexes
If you need both the item and its position, use enumerate().
rooms = ["Office 1", "Office 2", "Conference"]
for index, room in enumerate(rooms):
print(f"Room {index}: {room}")
Output:
Room 0: Office 1
Room 1: Office 2
Room 2: Conference
If you want to start counting from 1:
for index, room in enumerate(rooms, start=1):
print(f"Room {index}: {room}")
Output:
Room 1: Office 1
Room 2: Office 2
Room 3: Conference
Common Mistakes
Modifying the list while looping
# Don't do this
rooms = ["Office 1", "Office 2", "Office 3"]
for room in rooms:
if room == "Office 2":
rooms.remove(room) # Modifying while iterating causes issues
This can skip items or cause errors. Instead, build a new list:
# Do this
rooms = ["Office 1", "Office 2", "Office 3"]
filtered_rooms = []
for room in rooms:
if room != "Office 2":
filtered_rooms.append(room)
rooms = filtered_rooms
Wrong indentation
rooms = ["Office 1", "Office 2"]
for room in rooms:
print(room) # Not indented - error!
The code block must be indented.
Forgetting to create accumulator variables
# Wrong - compliant_count doesn't exist
for area in room_areas:
if area >= 400:
compliant_count += 1 # Error!
Initialize before the loop:
# Correct
compliant_count = 0
for area in room_areas:
if area >= 400:
compliant_count += 1
Using the loop variable after the loop
sheets = ["A-101", "A-102", "A-201"]
for sheet in sheets:
print(sheet)
print(f"Last sheet processed: {sheet}") # This works but is confusing
After the loop, sheet holds the last value ("A-201"). This works but can be confusing. If you need the last item, be explicit:
last_sheet = sheets[-1]
print(f"Last sheet: {last_sheet}")
Assignment
<div class="lesson-content__panel" markdown="1">
- Create a new file called
for_loops.py - Basic loop:
- Create a list:
rooms = ["Office 1", "Office 2", "Conference", "Break Room"] - Loop through and print each room
- Create a list:
- Conditional processing:
- List:
room_areas = [450.5, 380.2, 520.8, 410.3, 395.7] - Loop through and print warnings for rooms below 400m²
- List:
- Counting:
- Same list as above
- Count how many rooms are compliant (>= 400m²)
- Print the count
- Building a filtered list:
- Same list
- Create a new list with only large rooms (>= 500m²)
- Print the new list
- Calculating totals:
- Loop through the areas
- Calculate total area
- Calculate average area
- Print both
- Categorization:
- Create three empty lists: small, standard, large
- Loop through room_areas
- Categorize each: < 400 = small, 400-600 = standard, > 600 = large
- Print how many in each category
- Sheet naming:
- List:
sheets = ["101", "102", "201", "202"] - Loop through and create file names: "A-{number}_Plan.pdf"
- Store in a new list
- Print all file names
- List:
- Using range():
- Loop from 1 to 10 (floors)
- Print "Floor {number}"
- Real scenario - Compliance report:
- Areas:
[450.5, 380.2, 520.8, 410.3, 395.7] - Minimum: 400m²
- Loop through and print each area with status (Compliant/Non-compliant)
- Count total compliant and non-compliant
- Print summary
- Areas:
</div>
Knowledge Check
The following questions are an opportunity to reflect on key topics in this lesson.
- <a class="knowledge-check-link" href="#basic-for-loop">What does a for loop do?</a>
- <a class="knowledge-check-link" href="#the-syntax">What are the required parts of a for loop?</a>
- <a class="knowledge-check-link" href="#how-it-works">How does Python process a for loop?</a>
- <a class="knowledge-check-link" href="#building-new-lists">How do you create a filtered list using a loop?</a>
- <a class="knowledge-check-link" href="#counting-and-accumulating">How do you count items that meet a condition?</a>
- <a class="knowledge-check-link" href="#the-range-function">What does range(5) produce?</a>
- <a class="knowledge-check-link" href="#looping-with-indexes">How do you get both the index and the item in a loop?</a>
- <a class="knowledge-check-link" href="#common-mistakes">Why shouldn't you modify a list while looping through it?</a>
Additional Resources
This section contains helpful links to related content. It isn't required, so consider it supplemental.
- Python's official for loop documentation covers additional details and examples
- Real Python's guide to for loops provides comprehensive coverage with architectural patterns
- Python Tutor lets you visualize how loops execute step by step