The Python for Loop
The for loop in Python is a fundamental control structure used for definite iteration. This means you use it when you want to repeat a block of code a specific number of times, typically by iterating over a sequence like a list, tuple, string, or a range of numbers.
Think of it as a way to say, “For each item in this collection, do this action.”
Basic Syntax
The syntax of a for loop is clean and readable:
for variable_name in iterable:
# Code block to be executed for each item
# This block is indentedfor: The keyword that starts the loop.variable_name: A temporary variable that holds the current item from the iterable in each iteration. You can name it anything you like (e.g.,item,num,char).in: The keyword that separates the variable from the iterable.iterable: An object that can be looped over, such as a list, string, tuple, dictionary, or arangeobject.:: The colon that marks the end of the loop declaration.- Indented Block: The code to be executed in each iteration. Indentation (usually 4 spaces) is how Python knows this code belongs to the loop.
Iterating Over Different Sequences
The for loop is incredibly versatile. Let’s see how it works with different types of data.
Iterating Over a List
This is the most common use case. The loop goes through each element of the list one by one.
fruits = ["Apple", "Banana", "Cherry"]
print("Our fruit basket contains:")
for fruit in fruits:
print(f"- {fruit}")Output:
Our fruit basket contains:
- Apple
- Banana
- CherryThe range() Function: Your Best Friend for Loops
Often, you don’t have a sequence to loop over, but you want to repeat an action a certain number of times. The range() function is perfect for this. It generates a sequence of numbers on the fly.
Syntax of range()
The range() function can take one, two, or three arguments:
range(stop): Generates numbers from0up to (but not including)stop.range(start, stop): Generates numbers fromstartup to (but not including)stop.range(start, stop, step): Generates numbers fromstartup tostop, incrementing bystep.
Examples with range()
Example 1: Simple Repetition
To run a block of code 5 times, you use range(5).
Pyground
Print 'Hello, World!' 5 times using a for loop and range.
Expected Output:
Repetition #1: Hello, World! Repetition #2: Hello, World! Repetition #3: Hello, World! Repetition #4: Hello, World! Repetition #5: Hello, World!
Output:
The variable i is a common convention for the loop counter, short for “index.”
Example 2: Custom Start and Stop
To generate numbers from 1 to 10 (inclusive), you need range(1, 11).
Pyground
Print numbers from 1 to 10.
Expected Output:
1 2 3 4 5 6 7 8 9 10
Output:
Example 3: Using a Step
To print only the even numbers from 2 to 10, you can use a step of 2.
Pyground
Print all even numbers from 2 to 10.
Expected Output:
2 4 6 8 10
Output:
Example 4: Counting Downwards
To count backward, you need a negative step.
Pyground
Create a countdown from 5 down to 1.
Expected Output:
5 4 3 2 1 Liftoff!
Output:
Nested for Loops
You can put one for loop inside another. This is called a nested loop. It’s useful for working with 2D data structures (like a grid or matrix) or for creating combinations.
The inner loop will complete all its iterations for each single iteration of the outer loop.
Example: Printing a Multiplication Table
Pyground
Generate a multiplication table for numbers 1 through 3.
Expected Output:
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 --- 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 --- 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 ---
Output:
Be careful with nested loops. If the outer loop runs N times and the inner loop runs M times, the code inside the inner loop will execute N * M times. This can become very slow if N and M are large.
The for-else Clause
This is a lesser-known but useful feature of Python loops. The else block in a for loop is executed only if the loop completes all its iterations without being terminated by a break statement.
It’s useful for code that needs to run only when a search or process finishes “naturally.”
Example: Searching for an Item
Pyground
Search for the number 5 in a list. If found, print 'Found it!' and break. If the loop finishes without finding it, print 'Not found.'
Expected Output:
5 was not found in the list.
Output:
Now, let’s try a case where the number is found:
Pyground
Search for the number 4 in a list. If found, print 'Found it!' and break.
Expected Output:
Found it! The number is 4.
Output:
Practice Problems
Problem 1: Sum of Numbers
Write a program to calculate the sum of all numbers from 1 to 100.
Pyground
Calculate the sum of all numbers from 1 to 100.
Expected Output:
The sum of numbers from 1 to 100 is: 5050
Output:
Problem 2: Count Vowels in a String
Write a program that counts the number of vowels (a, e, i, o, u) in a given string.
Pyground
Count the number of vowels in the string 'hello world'.
Expected Output:
The number of vowels is: 3