Iterating collections
Working with collections is only useful if we can process everything they contain. Iteration is how Python lets us move through lists and dictionaries one element at a time. This shows up constantly in real programs, especially when generating output from data.
Iterating over lists using for
A list represents an ordered sequence of values. The most direct way to work with every item in a list is a for loop.
planets = ["Mercury", "Venus", "Earth", "Mars"]
for planet in planets:
print(planet)
On each pass through the loop, the variable planet refers to the next item in the list. This pattern is the default way to process lists in Python.
Iterating over dictionary keys and values
A dictionary stores data as key–value pairs. When we iterate over a dictionary, we usually want either the keys, the values, or both.
moons = {
"Earth": 1,
"Mars": 2,
"Jupiter": 79
}
for planet, count in moons.items():
print(planet, "has", count, "moons")
The items() method lets us work with each key and its associated value together, which is often the most useful form when handling structured data.
Using iteration to process all elements
Iteration lets us apply the same operation to every element in a collection. This is how data turns into output.
pages = ["index.html", "mars.html", "jupiter.html"]
for page in pages:
print("<li>" + page + "</li>")
Here, each element is transformed in the same way, producing repeated output without duplicated code.
Combining iteration with conditional logic
Loops often work alongside if statements to handle only certain elements.
planets = ["Mercury", "Venus", "Earth", "Mars"]
for planet in planets:
if planet.startswith("M"):
print(planet)
This combination lets us filter, select, or treat elements differently while still processing the entire collection.
Performing simple aggregate operations
Iteration also makes it possible to compute summary values, such as totals or counts.
moon_counts = [1, 2, 79]
total = 0
for count in moon_counts:
total = total + count
print(total)
This pattern appears frequently when collecting results from data before generating output or making decisions.
Conclusion
At this point, we know how to move through lists and dictionaries, process every element they contain, and combine iteration with conditions and simple calculations. That’s enough to turn collections into working program behavior, which is exactly what real Python programs rely on.