Hello! Welcome to your ninth lesson.
In our last lesson, we took a deep dive into Python lists. You learned how to create them, access individual items using indexing, select sub-lists with slicing, and modify them with methods like append() and pop(). This gave you the tools to manage a collection of data.
But what if you need to perform an action on every single item in that collection? For example, how would you print every task in your to-do list, or find the sum of all numbers in a list? Doing this one by one is impractical.
This lesson introduces one of the most fundamental concepts in programming: iteration. You will learn how to use for loops to systematically go through sequences like lists, strings, and tuples, unlocking the ability to process large amounts of data efficiently. This is a critical skill for building any algorithm.
1. The Need for Repetition: Introducing the for Loop
Imagine you have a list of numbers and you want to print each one on a new line. Based on what you learned, you might write this:
my_numbers = [10, 20, 30, 40]
print(my_numbers[0])
print(my_numbers[1])
print(my_numbers[2])
print(my_numbers[3])
This works, but it's repetitive and clumsy. What if the list had 100 numbers? This approach is not scalable. This is where loops come in. A for loop lets you execute a block of code once for each item in a sequence.
The article below gives a great introduction to why loops are so useful.
Getting started with Python for loops
Read the introduction of this article from Scaleway to see a clear comparison between code with and without a loop.
Read only the "Introduction" section. Notice how a five-line block of if statements is replaced by a concise three-line for loop.
The basic structure, or syntax, of a for loop in Python is simple and readable:
for variable_name in iterable:
# Code to execute for each item
# This block must be indented
forandinare keywords.iterableis the sequence you want to go through (like a list or a string).variable_nameis a temporary variable that holds the current item from the iterable in each pass of the loop. You can name it anything you like, but it's best to choose a descriptive name.
The concept of an "iterable" is central here. For now, you can think of it as any object that contains a sequence of items. Let's get a more formal definition.
Python for Loops: The Pythonic Way
This article from Real Python provides a clear definition of the for loop syntax and the concept of an iterable.
Read the section "Getting Started With the Python for Loop". Pay close attention to the syntax breakdown and the definition of an iterable at the end of the section.
This flowchart visualizes how a for loop works. It checks if there's a next item, processes it, and repeats until the sequence is finished.

2. Iterating Over Common Sequences
The for loop works consistently across different types of sequences. Let's see it in action.
First, watch this short video for a demonstration of looping through a list of numbers.
Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops
This clip from a Corey Schafer tutorial demonstrates the basic for loop with a list.
Watch from 00:20 to 00:59. Notice how the loop variable num takes on the value of each item in the nums list, one by one.
As you saw, the loop variable num holds 1, then 2, then 3, and so on, until the list nums is exhausted. This same principle applies to other sequences you've encountered.
- Lists: You can iterate over any list, no matter what data types it contains.
- Strings: A
forloop will iterate over each character in the string. - Tuples: Tuples are ordered collections just like lists, but they are immutable (meaning they cannot be changed after creation). You create them with parentheses
(). For looping purposes, they behave exactly like lists.
The following reading expands on this with clear examples for each type.
Python for Loops: The Pythonic Way
Now, read this section from the Real Python article to see examples of iterating over lists, tuples, and strings.
Read the subsection titled "Sequences: Lists, Tuples, Strings, and Ranges". You can skim the part about ranges for now, as we'll cover that next.
Here are some code examples to solidify your understanding. Try running them yourself!
# Iterating over a list of strings
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like to eat {fruit}s.")
print("---")
# Iterating over a string
my_name = "Alex"
for char in my_name:
print(char)
print("---")
# Iterating over a tuple of numbers
point = (10, 20, 30) # A 3D coordinate
for coordinate in point:
print(f"Coordinate value: {coordinate}")
3. Repeating a Specific Number of Times with range()
Sometimes you don't have a sequence to loop over, but you want to repeat an action a specific number of times. Python's built-in range() function is perfect for this. It generates a sequence of numbers that you can use in a for loop.
The range() function can be used in a few ways:
range(stop): Generates numbers from0up to (but not including)stop.range(start, stop): Generates numbers fromstartup tostop - 1.range(start, stop, step): Generates numbers fromstarttostop - 1, incrementing bystep.
Let's watch a quick video to see how this works.
Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops
This video clip clearly demonstrates how to use range() to loop a certain number of times.
Watch from 05:01 to 06:27. Pay attention to how range(10) produces numbers from 0 to 9, and how range(1, 11) is used to get numbers from 1 to 10.
Here are examples of the three forms of range():
# Example 1: range(stop)
print("Countdown:")
for i in range(3):
print(i) # Prints 0, 1, 2
print("---")
# Example 2: range(start, stop)
print("Numbers from 5 to 7:")
for i in range(5, 8):
print(i) # Prints 5, 6, 7
print("---")
# Example 3: range(start, stop, step)
print("Even numbers under 10:")
for i in range(0, 10, 2):
print(i) # Prints 0, 2, 4, 6, 8
4. Nested Loops: A Loop Inside a Loop
You can place one loop inside another. This is called a nested loop. It's useful for working with 2D data (like a grid or a matrix) or for generating combinations of items from two different sequences.
For every single iteration of the "outer loop", the "inner loop" will run completely from start to finish.
This video shows a simple example of generating pairs.
Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops
This clip demonstrates a nested loop, showing how an inner loop runs for each step of an outer loop.
Watch from 03:47 to 05:01. Observe how for each num, the code loops through every letter before moving to the next num.
A common use case is iterating through a list of lists, like a tic-tac-toe board:
board = [
['X', 'O', 'X'],
['O', 'X', 'O'],
['O', 'O', 'X']
]
# The outer loop gets each row
for row in board:
print(f"Processing row: {row}")
# The inner loop gets each cell in the current row
for cell in row:
print(f" Cell value: {cell}")
5. Practice Challenge: Data Analysis
Let's combine everything you've learned: loops, conditionals, and list methods. You are given a list of daily temperature readings for a week. Your task is to perform a simple analysis.
Given data:temperatures = [25.2, 18.3, 29.5, 15.0, 32.1, 12.8, 20.0]
Your tasks:
-
Calculate the average temperature:
- Initialize a variable
total_tempto0.0. - Use a
forloop to iterate through thetemperatureslist and add each temperature tototal_temp. - After the loop, calculate the average by dividing
total_tempby the number of days (you can uselen(temperatures)for this). - Print the average temperature.
- Initialize a variable
-
Identify the hot days:
- Create a new, empty list called
hot_days. - Use another
forloop to iterate through thetemperatureslist. - Inside the loop, use an
ifstatement to check if the temperature is greater than25.0. - If it is, use the
.append()method to add that temperature to yourhot_dayslist. - After the loop, print the
hot_dayslist.
- Create a new, empty list called
Write your code in a Python file and run it to see the results.
Click here to see the complete solution
temperatures = [25.2, 18.3, 29.5, 15.0, 32.1, 12.8, 20.0]
# Task 1: Calculate the average temperature
total_temp = 0.0
for temp in temperatures:
total_temp += temp # This is a shorthand for total_temp = total_temp + temp
average_temp = total_temp / len(temperatures)
print(f"The average temperature is: {average_temp:.2f}") # Formats to 2 decimal places
print("---")
# Task 2: Identify the hot days
hot_days = []
for temp in temperatures:
if temp > 25.0:
hot_days.append(temp)
print(f"The hot days were: {hot_days}")
# Expected Output:
# The average temperature is: 23.27
# ---
# The hot days were: [25.2, 29.5, 32.1]
Conclusion
Great job! You've mastered iteration, a cornerstone of programming. You can now automatically process every item in a sequence, which is essential for nearly every algorithm you'll write.
Key Takeaways:
forloops are used to repeat a block of code for each item in an iterable (like a list, string, or tuple).- The syntax is
for item in iterable:. Theitemvariable holds the current element in each iteration. - The
range()function generates a sequence of numbers, allowing you to loop a specific number of times. - Nested loops (a loop inside another loop) are used to process 2D data structures or create combinations.
- You can combine loops with
ifstatements to selectively process items in a sequence.
The practice challenge involved creating a new list based on a condition applied to an existing list. This is a very common pattern. In the next lesson, we will explore list comprehensions, a powerful and "Pythonic" shorthand for creating new lists from existing ones, often in a single, readable line of code.