animals = ["dog", "cat", "rabbit", "elephant", "tiger"]
for animal in animals:
print(f"I have a {animal}.")I have a dog.
I have a cat.
I have a rabbit.
I have a elephant.
I have a tiger.
for Loopsfor loop is and its syntaxrange() and enumerate() workfor Loops in Pythonfor loops iterate over a sequence (such as a list, tuple, string, dictionary, set, or range) and execute a block of code for each item in that sequence.
Syntax
for keyword is followed by a variable name (e.g., item) that receives the current element on each iteration.in keyword points to the sequence or iterable object.:) marks the start of the loop body.Example:
When you iterate directly over a dictionary, Python defaults to looping through its keys. However, you can also iterate over its values or both keys and values together using dictionary methods.
student_scores = {
"Alice": 85,
"Bob": 92,
"Charlie": 78
}
# 1. Loop through keys (default behaviour)
print("Keys:")
for name in student_scores:
print(name)
# 2. Loop through values using .values()
print("\nValues:")
for score in student_scores.values():
print(score)
# 3. Loop through key-value pairs using .items()
print("\nKey-Value Pairs:")
for name, score in student_scores.items():
print(f"{name} scored {score}%")Keys:
Alice
Bob
Charlie
Values:
85
92
78
Key-Value Pairs:
Alice scored 85%
Bob scored 92%
Charlie scored 78%
range()The range() function generates a sequence of numbers. Beginners often expect range(5) to produce a list of numbers directly, but let’s test what happens if you print it:
What is a range object?
Instead of generating all numbers in memory at once, range() creates a range object. This object generates each number on-the-fly as requested (a concept known as lazy evaluation).
To inspect the numbers contained inside a range object, you can convert it to a list:
How for loops use range()
When used in a for loop, the loop requests numbers from the range object one by one:
Syntax Options for range()
The syntax for range() is range(start=0, stop, step=1):
range(stop): Starts at 0 by default and goes up to, but does not include, stop.range(start, stop): Starts at start and goes up to, but does not include, stop.range(start, stop, step): Increments by step on each iteration, with the default step being 1.2 3 4 5
0 2 4 6 8
Combining range() and len()
You can combine range() and len() to loop using index positions:
enumerate()While range(len(...)) works for index-based access, Python provides a cleaner tool called enumerate().
If you try printing an enumerate call directly:
Just like range(), enumerate() produces an object that yields values on demand. Converting it to a list shows what it generates under the hood:
Each element is a tuple containing (index, item).
Using enumerate() in a for loop
In a for loop, Python unpacks these two-element tuples directly into two variables:
Animal 0: dog
Animal 1: cat
Animal 2: rabbit
Animal 3: elephant
You can also specify a custom starting index using start:
#1 - dog
#2 - cat
#3 - rabbit
#4 - elephant
Benefits of enumerate():
range(len(...)).Level:
Given a dictionary of shop items and their prices in pounds, write a for loop using .items() to print each item’s price and calculate the total cost of all items.
Level:
Given the following list of tasks, use enumerate() with start=1 to print a formatted to-do list:
Expected Output:
Task 1: Write report
Task 2: Send emails
Task 3: Review code
Task 4: Attend meeting
List comprehensions provide a concise way to create lists using for loops in a single line.
Syntax:
Level:
Convert the list of animals to uppercase using a list comprehension:
Level:
In the expense calculator, the function in the summary.py script iterates through the expenses to generate a summary. Modify display_summary() to use enumerate() to print a numbered summary and test your script in the Jupyter notebook.
def display_summary(expenses):
"""Uses enumerate to iterate through the data and print a numbered report."""
print("\n--- Expense Summary ---")
for index, item in enumerate(expenses, start=1):
category = item[0]
amount = item[1]
print(f"{index}. Category: {category.capitalize()} | Amount: £{amount:.2f}")
print("-----------------------\n")
# Testing the updated function
sample_expenses = [["food", 20.50], ["transport", 10.00], ["entertainment", 90.00]]
display_summary(sample_expenses)
--- Expense Summary ---
1. Category: Food | Amount: £20.50
2. Category: Transport | Amount: £10.00
3. Category: Entertainment | Amount: £90.00
-----------------------
for loops iterate through elements of sequences (lists, strings, ranges, dictionaries)..values() for values and .items() for key-value pairs.range() returns an iterable range object (not a pre-built list), generating numbers on demand.enumerate() yields (index, item) pairs, making indexed loops cleaner and safer.