Iterables
We briefly touched on the word iterable in the previous lessons. Now we are going to look at it properly. An iterable is simply any object in Python that can be stepped through one item at a time. If Python can loop over it, it is an iterable.
You have already worked with most of these. Here is the full list of the built in iterables in Python:
- Strings
"hello"each character is one item - Lists
[1, 2, 3]each element is one item - Tuples
(1, 2, 3)each element is one item - Sets
{1, 2, 3}each element is one item, unordered - Dictionaries
{"key": "value"}each key is one item by default - Ranges
range(10)each number in the range is one item - Files each line in a file is one item
What they all have in common is that Python can hand you one item at a time and keep track of where it is in the sequence. This is exactly what a for loop does behind the scenes. Each time the loop runs it asks the iterable for the next item until there are no items left.
The Vocabulary of Iteration
As you progress in Python, the way you talk about your code becomes just as important as the code itself. Understanding the correct terminology means you can read documentation, follow tutorials, and communicate with other developers without getting lost.
Here are the three terms you need to know:
- Iterable the collection itself. The list, tuple, string, set, or dictionary that holds the items. This is the thing you loop over.
- Iterate the action. When you loop over a collection you are iterating over it. Each pass through the loop is one iteration.
- Item the individual value you receive on each iteration. One item at a time, checked one by one until the collection is exhausted.
So when a developer says "I am iterating over a list" they mean they are looping through it one item at a time. When they say "the iterable is a tuple" they mean the tuple is the collection being looped over. This is the language you will see in documentation, Stack Overflow answers, and code reviews so it is worth getting comfortable with it now.
In the example below we are iterating over two iterables at the same time using a nested loop. The outer iterable is a tuple of numbers and the inner iterable is a tuple of letters. For every number, Python iterates over every letter.
Iterating Over a Dictionary
Dictionaries behave slightly differently to other iterables. When you iterate over a dictionary directly, Python returns the keys only by default. To access the values or both the keys and values together, you need to use one of three built in dictionary methods.
Try the example below and then we will look at how to get more out of our dictionary.
As you can see, iterating directly over the dictionary only returns the keys. Here are the three methods you need to know and you will use them constantly throughout your coding journey:
-
user.keys()returns the keys only. This is more explicit and readable than just iterating over the dictionary directly and makes your intention clear to anyone reading your code. -
user.values()returns the values only, with no keys. -
user.items()returns both the key and the value together as a tuple on each iteration.
Try each of the following in the box below and run it each time:
for item in user.keys():for item in user.values():for item in user.items():
When using .items() a very common pattern is to unpack
the tuple directly in the loop using two variables. Instead of
receiving a tuple on each iteration you receive the key and the value
as separate variables. You will see this constantly in real world Python code.
The variable names are completely up to you. key, value
is the most readable option, but shorthand like k, v is
also widely used. Use whatever makes the most sense in the context of
your code.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named iterables.py in your part45 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Iterating Over a Dictionary
-
Task: Create the following dictionary:
car = {'make': 'Toyota', 'model': 'Supra', 'year': 1998, 'colour': 'red'}. -
Goal: Write three separate for loops. The first
should print only the keys using
.keys(). The second should print only the values using.values(). The third should print both the key and value using.items(). Write a comment above each loop explaining what it returns and why.
Exercise 2: Key Value Unpacking
-
Task: Create the following dictionary:
scores = {'Eric': 95, 'Sarah': 87, 'John': 72, 'Pete': 90}. -
Goal: Use
for key, value in scores.items()to print each student name and their score in the following format:Eric scored 95. Write a comment explaining what unpacking means and why it is more useful than iterating over the dictionary directly.
Exercise 3: Iterating with a Condition
-
Task: Create the following dictionary:
stock = {'apples': 50, 'bananas': 0, 'oranges': 30, 'grapes': 0, 'mangoes': 15}. -
Goal: Use
for k, v in stock.items()and a conditional statement to print only the items that are out of stock. The output should readbananas is out of stock. Write a comment explaining how the loop and the condition work together.
Exercise 4: Iterating Over Mixed Iterables
-
Task: Create the following three iterables:
name = 'Python',numbers = (1, 2, 3, 4, 5),languages = ['JavaScript', 'C++', 'Ruby']. - Goal: Write a separate for loop for each one and print every item. Write a comment above each loop identifying what type of iterable it is and what one item represents in each case.
Exercise 5: Build a Summary
-
Task: Create the following dictionary:
profile = {'username': 'flat_eric', 'age': 27, 'language': 'Python', 'is_student': True}. -
Goal: Use
for k, v in profile.items()to print a summary of the profile in the following format:username: flat_eric. Then write a second loop that prints only the keys where the value is truthy. Write a comment explaining which keys are skipped and why.
Don't Forget to commit and Push!