For Loops
For loops are Python's most elegant and powerful iteration tool. They automatically iterate through sequences like lists, strings, and ranges with clean, readable syntax. Unlike while loops that focus on conditions, for loops excel at processing each item in a collection one by one.
For loops make data processing intuitive and efficient - perfect for analyzing lists, processing text, or working with any collection of data.
# Basic for loop examples
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Iterating through a string
word = "Python"
for letter in word:
print(f"Letter: {letter}")
# Using range for counting
for number in range(1, 4):
print(f"Number: {number}")
Basic For Loop Syntax
A for loop consists of the for
keyword, a variable name, the in
keyword, a sequence to iterate over, a colon, and an indented code block. Python automatically assigns each item in the sequence to the variable during each iteration.
Simple List Processing
Direct iteration through list elements for straightforward data processing:
# Processing a list of scores
scores = [85, 92, 78, 96]
for score in scores:
if score >= 90:
print(f"Excellent: {score}")
else:
print(f"Good: {score}")
String Character Processing
Character-by-character text analysis for string manipulation tasks:
# Counting vowels in text
text = "Hello World"
vowel_count = 0
for char in text:
if char.lower() in "aeiou":
vowel_count += 1
print(f"Vowels found: {vowel_count}")
Working with Ranges
The range()
function creates sequences of numbers perfect for for loops. Range is especially useful when you need to repeat an action a specific number of times or work with numeric sequences.
Basic Counting
Simple numeric iteration for repetitive tasks:
# Repeat an action 5 times
for i in range(5):
print(f"Step {i + 1}")
# 5 Count from 1 to
for num in range(1, 6):
print(f"Number: {num}")
Custom Step Patterns
Specialized counting with custom increments:
# 10 Even numbers from 0 to
for i in range(0, 11, 2):
print(f"Even: {i}")
# 1 Countdown from 5 to
for i in range(5, 0, -1):
print(f"T-minus {i}")
🔁 Quick For Loop Practice
Let's practice using for loops with enumerate to get both position and value!
Hands-on Exercise
Use a for loop with enumerate to print each fruit with its position number.
# For Loop Practice - Position and value!
fruits = ["apple", "banana", "cherry", "date"]
# TODO: Your code here: use enumerate to print each fruit with its position
# Expected output: "Fruit 1: apple", "Fruit 2: banana", etc.
Solution and Explanation 💡
Click to see the complete solution
# For Loop Practice - Solution
fruits = ["apple", "banana", "cherry", "date"]
for index, fruit in enumerate(fruits):
print(f"Fruit {index + 1}: {fruit}")
Key Learning Points:
- 📌 enumerate function: Returns both index and value from a list
- 📌 Multiple variables: Unpack index and item in the same loop
- 📌 Position tracking: Index starts at 0, add 1 for human-friendly numbering
- 📌 Tuple unpacking: Python automatically assigns index and value to separate variables
Iterating with Indices
Sometimes you need both the item and its position. The enumerate()
function provides both the index and value during iteration, making it easy to track positions.
Index-Value Pairs
Accessing both position and content simultaneously:
# Getting position and value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Position {index}: {fruit}")
# 1 Starting count from
for position, fruit in enumerate(fruits, start=1):
print(f"#{position}: {fruit}")
Position-Based Logic
Using index for conditional processing:
# Alternating pattern based on position
words = ["hello", "world", "python", "code"]
for i, word in enumerate(words):
if i % 2 == 0:
print(f"Even position: {word}")
else:
print(f"Odd position: {word}")
Loop Control in For Loops
For loops support break
and continue
statements for controlling execution flow, just like while loops. These statements help handle special cases and create sophisticated iteration logic.
Early Exit with Break
Immediate loop termination upon meeting conditions:
# 5 Find first number greater than
numbers = [1, 2, 3, 6, 7, 8]
for num in numbers:
if num > 5:
print(f"Found: {num}")
break
print(f"Checking: {num}")
Selective Processing with Continue
Skip unwanted items during processing:
# Process only even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
for num in numbers:
if num % 2 != 0:
continue # Skip odd numbers
print(f"Even number: {num}")
For Loop with Else
Python's for loops support an optional else
clause that executes only if the loop completes normally (without encountering a break statement). This feature is perfect for search operations.
Search with Fallback
Target searching with automatic "not found" handling:
# Search for a target value
target = 7
numbers = [1, 3, 5, 9, 11]
for num in numbers:
if num == target:
print(f"Found {target}!")
break
else:
print(f"{target} not found in the list")
Validation Pattern
Complete validation with success confirmation:
# Check if all grades are passing
grades = [85, 92, 78, 96, 88]
for grade in grades:
if grade < 70:
print("Found failing grade")
break
else:
print("All grades are passing!")
Nested For Loops
For loops can be nested inside other for loops to handle multi-dimensional data or create patterns. Each inner loop completes all its iterations for every single iteration of the outer loop.
Simple Pattern Creation
Creating visual patterns with nested loops:
# Right triangle pattern
for i in range(4):
for j in range(i + 1):
print("*", end="")
print() # New line after each row
Matrix Processing
Working with 2D data structures:
# Processing a 2D matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=" ")
print() # New line after each row
Common For Loop Patterns
Several patterns appear frequently when using for loops. Learning these patterns helps you solve common programming problems efficiently.
Value Accumulation
Building up totals through iteration:
# Sum all numbers
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}")
# Count specific items
text = "hello world"
vowel_count = 0
for char in text:
if char.lower() in "aeiou":
vowel_count += 1
print(f"Vowels: {vowel_count}")
Data Transformation
Creating new collections from existing data:
# Create list of squares
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
squares.append(num ** 2)
print(f"Squares: {squares}")
# Word lengths
words = ["hello", "world", "python"]
lengths = []
for word in words:
lengths.append(len(word))
print(f"Lengths: {lengths}")
For Loops vs List Comprehensions
Python offers list comprehensions as a concise alternative to for loops when creating new lists. Understanding when to use each approach helps you write more Pythonic code.
Comparison Example
Traditional loop vs comprehension approach:
numbers = [1, 2, 3, 4, 5]
# Traditional for loop
squares_loop = []
for num in numbers:
squares_loop.append(num ** 2)
# List comprehension
squares_comp = [num ** 2 for num in numbers]
print(f"Loop result: {squares_loop}")
print(f"Comprehension: {squares_comp}")
For Loop Reference
Pattern | Purpose | Example | Use Case |
---|---|---|---|
for item in sequence: | Basic iteration | for x in [1,2,3]: | Process each item |
for i in range(n): | Count-controlled | for i in range(10): | Repeat n times |
for i, item in enumerate(seq): | Index and value | for i, x in enumerate(list): | Need position |
for item in seq: ... else: | Search pattern | for x in list: ... else: | Handle "not found" |
Choose the pattern that best fits your data processing needs.
Take Quiz
Test your understanding of for loops:
What's Next?
Now that you understand for loops, you're ready to learn about loop control techniques. This includes advanced break and continue usage, nested loop control, and sophisticated iteration patterns that give you precise control over loop execution.
Ready to continue? Check out our lesson on Loop Control to master advanced loop management techniques! 🎮
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.