- What for loops are ā iterating over sequences
- Syntax and structure ā writing for loops correctly
- range() function ā generating number sequences
- Iterating lists, strings, dictionaries ā working with data structures
- Real-world applications ā practical examples
- Best practices ā writing efficient for loops
- Hands-on practice with the interactive editor
What is a For Loop?
A for loop in Python is used to iterate over a sequence of elements. Unlike a while loop that runs based on a condition, a for loop runs for a specified number of times or over each item in a collection. It's the most common and convenient way to process lists, strings, tuples, dictionaries, and other iterable objects.
š” Key insight: For loops in Python are designed to be clean and readable. They automatically handle the iteration mechanics, making your code simpler and less error-prone than manual index management.
The for loop is incredibly versatile. You can use it to process items in a list, characters in a string, keys in a dictionary, or generate number sequences with the range() function. This makes it one of the most frequently used constructs in Python programming.
For Loop Syntax
The syntax of a for loop in Python is simple and intuitive:
# Basic for loop syntax
for variable in iterable:
# Code to execute for each item
print(variable)
# Example: Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Output:
# I like apple
# I like banana
# I like cherry
Key components of a for loop:
- for keyword ā starts the loop
- variable ā takes the value of each item in the sequence
- in keyword ā connects the variable to the sequence
- iterable ā the sequence to iterate over (list, string, range, etc.)
- colon ā marks the beginning of the loop body
- indented block ā code to execute for each item
The range() Function
The range() function is commonly used with for loops to generate sequences of numbers:
# range(stop) - generates numbers from 0 to stop-1
for i in range(5):
print(i, end=" ")
# Output: 0 1 2 3 4
# range(start, stop) - generates from start to stop-1
for i in range(2, 7):
print(i, end=" ")
# Output: 2 3 4 5 6
# range(start, stop, step) - with step size
for i in range(1, 11, 2):
print(i, end=" ")
# Output: 1 3 5 7 9
# range in reverse (using negative step)
for i in range(10, 0, -2):
print(i, end=" ")
# Output: 10 8 6 4 2
š Important: The range() function creates a sequence of numbers on-demand. It doesn't store all numbers in memory, making it efficient for large ranges.
Iterating Lists with For Loop
For loops are ideal for processing lists. Here are several ways to iterate lists:
# 1. Direct iteration over items
colors = ["red", "green", "blue"]
for color in colors:
print(color)
# 2. Iterating with index using range()
for i in range(len(colors)):
print(f"Index {i}: {colors[i]}")
# 3. Using enumerate() to get both index and value
for index, color in enumerate(colors):
print(f"Position {index}: {color}")
# 4. Processing list elements
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}")
# Output: Sum: 150
Iterating Strings with For Loop
Strings are sequences of characters, so for loops work naturally:
# Iterating characters
word = "Python"
for char in word:
print(char, end=" ")
# Output: P y t h o n
# Counting vowels in a string
text = "Hello World"
vowels = 0
for char in text.lower():
if char in 'aeiou':
vowels += 1
print(f"Vowels: {vowels}")
# Output: Vowels: 3
# Reversing a string
word = "Python"
reversed_word = ""
for char in word:
reversed_word = char + reversed_word
print(reversed_word)
# Output: nohtyP
Iterating Dictionaries with For Loop
Dictionaries allow iteration over keys, values, or both:
student = {"name": "Alice", "age": 25, "grade": "A"}
# Iterating keys (default)
for key in student:
print(f"{key}: {student[key]}")
# Iterating keys explicitly
for key in student.keys():
print(f"Key: {key}")
# Iterating values
for value in student.values():
print(f"Value: {value}")
# Iterating key-value pairs
for key, value in student.items():
print(f"{key} ā {value}")
# Output:
# name ā Alice
# age ā 25
# grade ā A
Real-World Examples
š” Use Case 1: Processing Student Grades
grades = [85, 92, 78, 90, 88, 76]
total = 0
highest = grades[0]
lowest = grades[0]
for grade in grades:
total += grade
if grade > highest:
highest = grade
if grade < lowest:
lowest = grade
average = total / len(grades)
print(f"Average: {average:.2f}")
print(f"Highest: {highest}")
print(f"Lowest: {lowest}")
# Output:
# Average: 84.83
# Highest: 92
# Lowest: 76
š” Use Case 2: Product Inventory Check
inventory = {
"laptop": 15,
"mouse": 45,
"keyboard": 22,
"monitor": 8
}
low_stock_items = []
for item, quantity in inventory.items():
if quantity < 10:
low_stock_items.append(item)
print("Low stock items:", low_stock_items)
# Output: Low stock items: ['monitor']
š” Use Case 3: Employee Salary Report
employees = [
{"name": "John", "salary": 75000},
{"name": "Sarah", "salary": 82000},
{"name": "Mike", "salary": 68000}
]
total_salary = 0
for emp in employees:
total_salary += emp["salary"]
print(f"{emp['name']}: ${emp['salary']}")
print(f"Total: ${total_salary}")
print(f"Average: ${total_salary / len(employees):.2f}")
# Output:
# John: $75000
# Sarah: $82000
# Mike: $68000
# Total: $225000
# Average: $75000.00
Best Practices & Pitfalls
ā ļø Common Pitfalls
- Modifying a list while iterating over it
- Using range(len()) when direct iteration works
- Forgetting to store values from iteration
- Using for loops for simple arithmetic sequences
ā Best Practices
- Use direct iteration when possible
- Use enumerate() when you need indices
- Use list comprehensions for transformations
- Keep loop bodies simple and focused
š” Optimization Tips
- Use break to exit early
- Use continue to skip items
- Consider generator expressions for large data
- Use built-in functions like sum(), max(), min()
Try It Yourself!
Experiment with for loops directly in your browser. Modify the code and see the results in real time.
FOR LOOP DEMONSTRATION
========================================
1. BASIC FOR LOOP (1 to 5)
1 2 3 4 5
2. ITERATING A LIST
- apple
- banana
- cherry
- mango
3. ITERATING A STRING
P y t h o n
4. ITERATING A DICTIONARY
name: Alice
age: 25
grade: A
5. SUM OF NUMBERS 1 TO 10
Total: 55
6. EVEN NUMBERS UP TO 20
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
ā Explore for loops!
š You've Learned Python For Loops!
You understand for loop syntax, range() function, iterating over lists, strings, and dictionaries. These are essential skills for Python programming!
Quick Quiz ā Test Your Knowledge
Let's see what you've learned about for loops:
Frequently Asked Questions
š¤ What's the difference between for and while loops?
š Can I use break and continue in for loops?
break exits the loop immediately, and continue skips the rest of the current iteration and moves to the next item. Both are commonly used in for loops for conditional control flow.
š What is the else clause in for loops?
else clause in a for loop executes when the loop completes without encountering a break statement. It's useful for checking if a loop completed all iterations or was interrupted. For example, searching for an item in a list.
š How do I iterate over a file with for loop?
for line in open('file.txt'): print(line)
š Can I create nested for loops?
š¦ What is the difference between range and xrange?
range() behaves like the old xrange() and is lazy ā it generates numbers on demand. xrange() doesn't exist in Python 3. In Python 2, range() creates a list, while xrange() creates a generator. Use range() in Python 3 for all cases.
š Where to Go From Here
Now that you've mastered for loops, here are the next topics to explore:
š For Loop Examples
Explore more advanced for loop examples.
Learn More āš Nested For Loop
Learn about for loops inside other for loops.
Learn More āā” Break, Continue, Else
Master loop control statements.
Learn More ā