Python language basics 18: looping through collections with foreach-loops
June 6, 2015 Leave a comment
Introduction
In the previous post we looked at the dictionary data structure in Python. We saw how a dictionary could be used to order a value to a key just like in a real language dictionary. In the post before that we discussed the list collection which is another important collection type in Python.
In this post we’ll see how to loop through each of the two collection types.
Looping through lists with a foreach-loop
By ‘looping’ we mean visiting each member of a collection one by one with the goal of performing some action on them. Another term often used in place of looping is iterating through a collection.
For-loops are basic building blocks in every popular programming language. They often come in two flavours: for-loops and foreach-loops. We’ll take up foreach-loops in this post as they are often used to loop through collections. We’ll look at the more traditional for-loops in the next post.
Foreach-loops are called “foreach” because as we iterate through the elements in the collection we want to do something with each of them. So “for each element in the collection execute this and this”.
Recall that we had the following list of sizes:
sizes = ["small", "medium", "large", "x-large"]
The following code will loop through the list and print the first character of each:
for size in sizes: print(size[0])
Here’s the printout:
s
m
l
x
The variable name “size” could be anything, don’t assume that it must the singular form of the list name. The below code works just as well:
for mickeyMouse in sizes: print(mickeyMouse[0])
However, it’s often the case and also logical to take the singular form of the list name in the loop for the individual elements like in “for country in countries”, “for animal in animals” etc.
Iterating through dictionaries with foreach-loops
Iterating through dictionaries is a very similar process. The loop variable will give us access to the key of each element. We can then use the key to access the value of the key-value pair as we saw in the post on dictionaries.
Recall the dictionary example from before:
sizes = {"S": "Small", "M": "Medium", "L": "Large", "XL": "X-Large"}
Here’s how we can print the key and value of each element in a for-loop:
for size in sizes: print("Key ", size, ", value: ", sizes[size])
…which prints the following:
Key L , value: Large
Key S , value: Small
Key M , value: Medium
Key XL , value: X-Large
You’ll notice that the loop didn’t go through the elements in the same order as in the “sizes” dictionary. If you run the foreach-loop multiple times you’ll notice that the order changes. Hence don’t assume anything about the sequence of the elements as you loop through a dictionary.
Read the next instalment of the series here.
Read all Python-related posts on this blog here.