🔄 Looping Through Lists
Looping through lists is one of the most common operations in Python programming. Whether you need to process each item, find specific elements, or perform calculations, understanding different iteration methods is essential for effective programming.
Python provides several powerful methods for looping through lists, each with its own advantages and use cases.
# Different ways to loop through lists
fruits = ["apple", "banana", "cherry", "date"]
# Simple for loop
print("Method 1 - Simple for loop:")
for fruit in fruits:
print(f"I like {fruit}")
# Loop with index using enumerate
print("\nMethod 2 - With index:")
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Loop with range and len
print("\nMethod 3 - Using range:")
for i in range(len(fruits)):
print(f"Position {i} has {fruits[i]}")
🌟 Basic For Loop Iteration
The most common and Pythonic way to loop through a list is using a simple for loop. This method gives you direct access to each element without worrying about indices.
Simple Value Processing
# Basic for loop examples
colors = ["red", "green", "blue", "yellow", "purple"]
# Print each color
print("Available colors:")
for color in colors:
print(f"- {color}")
Accumulating Values
# Process each item
numbers = [1, 2, 3, 4, 5]
total = 0
for number in numbers:
total += number
print(f"Sum of numbers: {total}")
Conditional Processing
# Conditional processing
grades = [85, 92, 78, 96, 88, 73, 91]
print("Grade analysis:")
for grade in grades:
if grade >= 90:
print(f"{grade} - Excellent!")
elif grade >= 80:
print(f"{grade} - Good")
else:
print(f"{grade} - Needs improvement")
📍 Looping with Index using enumerate()
Sometimes you need both the element and its position. The enumerate()
function provides both the index and the value in each iteration.
Basic Enumerate Usage
# Using enumerate for index and value
students = ["Alice", "Bob", "Charlie", "Diana"]
# Print with position numbers
print("Class roster:")
for index, student in enumerate(students):
print(f"{index + 1}. {student}")
Custom Starting Number
# Start enumerate from a different number
students = ["Alice", "Bob", "Charlie", "Diana"]
print("With custom starting number:")
for position, student in enumerate(students, start=1):
print(f"Student #{position}: {student}")
Finding Positions
# Find positions of specific items
fruits = ["apple", "banana", "apple", "cherry", "apple"]
apple_positions = []
for index, fruit in enumerate(fruits):
if fruit == "apple":
apple_positions.append(index)
print(f"Apples found at positions: {apple_positions}")
🎯 Advanced Iteration Techniques
Python offers several advanced techniques for iterating through lists that can make your code more efficient and readable.
Using zip() for Multiple Lists
# Iterate through multiple lists simultaneously
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
subjects = ["Math", "Science", "English"]
print("Student performance:")
for name, score, subject in zip(names, scores, subjects):
print(f"{name} scored {score} in {subject}")
List Comprehension with Conditions
# Process and filter in one step
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Create new list with processed even numbers
even_squares = [x**2 for x in numbers if x % 2 == 0]
print("Squares of even numbers:", even_squares)
Nested List Iteration
# Iterate through nested lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("Matrix elements:")
for row_index, row in enumerate(matrix):
for col_index, value in enumerate(row):
print(f"Position ({row_index}, {col_index}): {value}")
Hands-on Exercise
Create a function that finds all pairs of numbers in a list that add up to a target sum. Use nested loops to check all combinations.
def find_pairs(numbers, target_sum):
pairs = []
# TODO: Use nested loops to find all pairs that sum to target_sum
# Avoid checking the same pair twice by starting inner loop from i+1
# TODO: Your code here
return pairs
# Test the function
test_numbers = [1, 2, 3, 4, 5, 6]
target = 7
result = find_pairs(test_numbers, target)
print(f"Numbers: {test_numbers}")
print(f"Target sum: {target}")
print(f"Pairs that sum to {target}: {result}")
Solution and Explanation 💡
Click to see the complete solution
def find_pairs(numbers, target_sum):
pairs = []
# Use nested loops to find all pairs that sum to target_sum
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)): # Start from i+1 to avoid duplicates
if numbers[i] + numbers[j] == target_sum:
pairs.append((numbers[i], numbers[j]))
return pairs
# Test the function
test_numbers = [1, 2, 3, 4, 5, 6]
target = 7
result = find_pairs(test_numbers, target)
print(f"Numbers: {test_numbers}")
print(f"Target sum: {target}")
print(f"Pairs that sum to {target}: {result}")
Key Learning Points:
- 📌 Nested loops: Outer loop for first element, inner loop for second element
- 📌 Avoid duplicates: Start inner loop from
i + 1
to prevent checking same pairs - 📌 Tuple creation: Use
(a, b)
to store pairs as tuples - 📌 List building: Append matching pairs to results list
🎨 Common Iteration Patterns
Data Processing Pipeline
# Data processing pipeline
raw_data = [" Alice ", "BOB", "charlie", " DIANA "]
processed_data = []
print("Processing pipeline:")
for item in raw_data:
# Clean whitespace and normalize case
cleaned = item.strip().title()
processed_data.append(cleaned)
print(f"Processed: '{cleaned}'")
print("Final processed data:", processed_data)
Validation and Filtering
# Validation and filtering
user_inputs = ["alice@email.com", "invalid-email", "bob@test.org", "", "charlie@domain.com"]
valid_emails = []
invalid_count = 0
print("Email validation:")
for email in user_inputs:
if "@" in email and "." in email and len(email) > 5:
valid_emails.append(email)
print(f"✓ Valid: {email}")
else:
invalid_count += 1
print(f"✗ Invalid: {email}")
print(f"Valid emails: {valid_emails}")
print(f"Invalid count: {invalid_count}")
Accumulation and Statistics
# Calculate statistics
test_scores = [85, 92, 78, 96, 88, 73, 91, 87]
total = 0
count = 0
highest = test_scores[0]
lowest = test_scores[0]
print("Calculating statistics:")
for score in test_scores:
total += score
count += 1
if score > highest:
highest = score
if score < lowest:
lowest = score
average = total / count
print(f"Average: {average:.1f}")
print(f"Highest: {highest}")
print(f"Lowest: {lowest}")
Learn more about for loops for additional looping techniques and patterns.
Test Your Knowledge
Test what you've learned about looping through lists in Python:
What's Next?
Now that you know how to loop through lists effectively, you're ready to learn about list shortcuts. This includes powerful techniques, built-in functions, and Pythonic ways to work with lists more efficiently.
Ready to continue? Check out our lesson on List Shortcuts.
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.