Mastering Python For Loops
Iterating Over Sequences
Working with Sequences
In programming, we often need to perform an action on every item in a collection. Python makes this incredibly straightforward with the for loop. Instead of manually tracking an index number like in C++ or Java, Python's for loop directly accesses each element in a sequence.
This is often called a "for-each" loop in other languages. In Python, it's just the standard
forloop.
The basic structure looks like this: for item in sequence:. The item is a temporary variable that holds the current element from the sequence for each pass of the loop. The indented code block below it is executed once for each item. Let's look at how this works with a list of transactions.
transaction_amounts = [25.50, 12.35, 7.99, 105.00]
total = 0
for amount in transaction_amounts:
total += amount
print(f"The total is: {total}")
# Output: The total is: 150.84
Notice there are no counters or index variables like i. The loop handles grabbing each amount from the transaction_amounts list automatically. This same simple syntax works for tuples, too. This direct access is a core part of what makes Python code clean and readable. The loop works on any object that is an iterable—a collection of items that can be accessed one after another.
Strings and Dictionaries
Strings are just sequences of characters, so you can iterate over them directly. This is useful in fields like bioinformatics, where you might need to process a DNA sequence character by character.
dna_sequence = "AGTCGATT"
base_counts = {'A': 0, 'G': 0, 'T': 0, 'C': 0}
for base in dna_sequence:
if base in base_counts:
base_counts[base] += 1
print(base_counts)
# Output: {'A': 2, 'G': 2, 'T': 2, 'C': 1}
Dictionaries are a bit different because they store key-value pairs. If you loop directly over a dictionary, you'll get its keys. This is the default behavior and is often exactly what you need.
student_grades = {"Alice": 88, "Bob": 95, "Charlie": 72}
for student in student_grades:
print(student)
# Output:
# Alice
# Bob
# Charlie
To work with values or both keys and values, dictionaries have special methods. You can use my_dict.values() to iterate over just the values, or the very useful .items() method to iterate over key-value pairs, which are provided as tuples.
student_grades = {"Alice": 88, "Bob": 95, "Charlie": 72}
# Using .items() to get both key and value
for student, grade in student_grades.items():
print(f"{student} scored {grade}")
# Output:
# Alice scored 88
# Bob scored 95
# Charlie scored 72
This technique of assigning the two parts of the tuple (student, grade) to separate variables in the loop is called and is a common Pythonic pattern for clean, readable code.
To recap the main ways to loop over a dictionary:
| Method | What it Iterates Over | Example |
|---|---|---|
for k in my_dict: | Keys (default) | "Alice", "Bob", ... |
for v in my_dict.values(): | Values | 88, 95, 72 |
for k, v in my_dict.items(): | (Key, Value) tuples | ("Alice", 88), ... |
This ability to directly iterate over items rather than indices is a fundamental aspect of Python's design philosophy. It reduces boilerplate code, minimizes the chance of off-by-one errors, and makes the programmer's intent much clearer.
Ready to check your understanding?
What is the output of the following Python code?
my_string = "abc"
for char in my_string:
print(char)
When iterating directly over a dictionary using a for loop (e.g., for item in my_dict:), what does the loop variable item hold during each iteration by default?
By mastering the for...in loop, you unlock a powerful and efficient way to work with any sequence of data in Python.