Topic 13 of 58
for Loops
Overview
A for loop in Python is technically a 'for-each' loop. Instead of manually tracking an index number (like int i = 0), Python directly iterates over the items of any sequence or iterable (lists, strings, tuples, dictionaries, sets). This eliminates off-by-one errors and results in highly readable code. If you DO need a sequence of numbers, the built-in range() function generates them on the fly.
Syntax
python
fruits = ["apple", "banana", "cherry"]
# Direct iteration (Pythonic)
for fruit in fruits:
print(fruit)
# Iterating a specific number of times using range(start, stop, step)
for i in range(0, 5, 2):
print(i) # Outputs: 0, 2, 4 (stops before 5)
# Iterating over a string
for char in "Python":
print(char.upper())Common Pitfalls
- Modifying a list (adding or removing items) while iterating over it. This messes up internal indexing and causes items to be skipped. If you must modify, iterate over a copy:
for item in my_list[:]. - Misunderstanding
range(5). It yields 0, 1, 2, 3, 4. The stop value is always exclusive.
Interview Questions
Q:
How do you loop over a list and access both the item and its index simultaneously?
A:
Use the enumerate() function. Example: for index, value in enumerate(my_list):. It is much cleaner than using range(len(my_list)).
Real-World Example
Iterating through dictionary keys and values simultaneously.
example
python
employee_salaries = {"Alice": 90000, "Bob": 85000, "Charlie": 120000}
# The .items() method returns tuples of (key, value)
for name, salary in employee_salaries.items():
if salary > 100000:
print(f"{name} is a high earner.")Check Your Knowledge
Test your understanding of for Loops with these quick questions.