Loops: foreach loops (iterating over collections)
Following our exploration of Loops: while and do-while loops, this article focuses on what is often called a "foreach" loop in other languages. In Python, this is simply the standard for loop used to iterate over collections.
📚 Prerequisites
A basic understanding of Python's for loop and common collection types (lists, tuples, dictionaries, sets).
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ How to iterate over lists and tuples.
- ✅ How to iterate over dictionaries.
- ✅ How to iterate over sets.
- ✅ The concept of a "foreach" loop in Python.
🧠 Section 1: The "foreach" Loop in Python
Python doesn't have a separate foreach keyword like some other languages. Instead, the standard for loop serves the same purpose. It's used to iterate over the items of any sequence or collection.
💻 Section 2: Iterating Over Lists and Tuples
Iterating over lists and tuples is straightforward. The for loop will assign each item in the sequence to the loop variable.
Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Iterating over a tuple:
colors = ("red", "green", "blue")
for color in colors:
print(color)
🛠️ Section 3: Iterating Over Dictionaries
When you iterate over a dictionary, you can access its keys, values, or both.
Iterating over keys (the default):
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(key) # Output: a, b, c
Iterating over values:
for value in my_dict.values():
print(value) # Output: 1, 2, 3
Iterating over key-value pairs:
for key, value in my_dict.items():
print(f"key: {key}, value: {value}")
🔬 Section 4: Iterating Over Sets
You can iterate over a set using a for loop, just like with a list or tuple. However, remember that sets are unordered, so the order in which the items are accessed is not guaranteed.
my_set = {"apple", "banana", "cherry"}
for item in my_set:
print(item)
💡 Conclusion & Key Takeaways
You've now learned how to use Python's for loop to iterate over various collection types, which is a fundamental skill for any Python programmer.
Let's summarize the key takeaways:
- "foreach" in Python: The standard
forloop is used to iterate over collections. - Lists and Tuples: Iterate over each item in the sequence.
- Dictionaries: Iterate over keys, values, or key-value pairs.
- Sets: Iterate over each item in the set, but the order is not guaranteed.
Challenge Yourself:
Create a dictionary of your favorite foods and their ratings (e.g., "pizza": 10). Then, use a for loop to print each food and its rating.
➡️ Next Steps
In the next article, we'll learn about "Loop Control: break and continue".
Happy coding!
Glossary (Python Terms)
- Collection: A group of objects, such as a list, tuple, dictionary, or set.
- "foreach" loop: A loop that iterates over the items of a collection. In Python, this is the standard
forloop.