Iterables: what are they good for?
What is an iterable?
If you can write a for loop in Python to loop over something, that something is an iterable.
A list is an iterable:
>>> fruits = ['apple', 'lemon', 'pear', 'watermelon']
The usual way to iterate over something is to write a for loop:
>>> for fruit in fruits:
... print(fruit)
...
apple
lemon
pear
watermelon
As we loop over the fruits list above, we’re assigning the variable fruit to each item in the list and then doing something with it (printing in this case) inside the body of our loop.
The above for loop works, which means fruits is an iterable.
Types of iterables
What are some types of iterables that you can think of?
Lists:
>>> fruits
['apple', 'lemon', 'pear', 'watermelon']
Tuples:
>>> coordinates = (1, 8, 2)
Sets:
>>> colors = {'red', 'blue', 'yellow'}
Strings are iterable too! When we iterate over strings we get characters:
>>> greeting = "Hi y'all!"
>>> for c in greeting:
... print(c)
...
H
i
y
'
a
l
l
!
Dictionaries are also iterables?
>>> counts = {'purple': 3, 'blue': 1, 'green': 2}
What would we get if we looped over a dictionary?
Keys!
>>> for key in counts:
... print(key)
...
purple
blue
green
List Comprehensions
List comprehensions are a tool. Like all tools, you need to be able to identify opportunities to use them.
You can use list comprehensions whenever you see a “for loop” that loops over an iterable, transforming each item and adding it to a list.
Take this function:
>>> def square_all(numbers):
... squared_numbers = []
... for n in numbers:
... squared_numbers.append(n*n)
... return squared_numbers
...
>>> square_all([1, 2, 3, 4])
[1, 4, 9, 16]
>>> square_all((0, 1, 2))
[0, 1, 4]
This function has a for loop that turns one list (or any other iterable) into a new list.
We can rewrite this as a list comprehension:
>>> def square_all(numbers):
... return [n*n for n in numbers]
...
>>> square_all([1, 2, 3, 4])
[1, 4, 9, 16]
>>> square_all((0, 1, 2))
[0, 1, 4]
We can also use list comprehensions whenever we see a for loop that also excludes some values, using an if statement to filter out values that don’t meet a condition.
For more on comprehensions, see turning a loop into a comprehension.
Anywhere that you see a for loop looping over an iterable, doing something with it, and making a list as a result, consider whether a list comprehension might be appropriate instead.
Lazy iterables
What else is iterable?
Files are iterables. When we loop over files we get each line in the file.
>>> with open("my_file.txt") as file:
... for line in file:
... print(line.strip())
...
First line in the file
Second line
Third and final line
The built-in enumerate, reversed, and zip also return their own custom types of iterables:
>>> enumerate(fruits)
<enumerate object at 0x...>
>>> reversed(fruits)
<list_reverseiterator object at 0x...>
>>> zip([2, 1, 3], [4, 7, 11])
<zip object at 0x...>
We can loop over all those objects:
>>> for item in enumerate(fruits):
... print(item)
...
(0, 'apple')
(1, 'lemon')
(2, 'pear')
(3, 'watermelon')
>>> for item in reversed(fruits):
... print(item)
...
watermelon
pear
lemon
apple
>>> for item in zip([2, 1, 3], [4, 7, 11]):
... print(item)
...
(2, 4)
(1, 7)
(3, 11)
Remember… anything you can loop over is an iterable.
Custom iterable types are floating around all over the place in Python.
All iteration is the same
Iterables aren’t just for for loops.
The list constructor accepts any iterable and makes a list out of it:
>>> greeting = "Hi y'all!"
>>> coordinates = (1, 8, 2)
>>> list(greeting)
['H', 'i', ' ', 'y', "'", 'a', 'l', 'l', '!']
>>> list(coordinates)
[1, 8, 2]
Most functions that accept some types of iterables actually work with all types of iterables.
Comprehensions rely on iterability:
>>> [c for c in greeting if c.isalpha()]
['H', 'i', 'y', 'a', 'l', 'l']
Tuple unpacking also relies on iterability. So any object you can iterate over can be used with tuple unpacking. Even something odd, like a string or a dictionary:
>>> counts = {'purple': 3, 'blue': 1, 'green': 2}
>>> a, b, c = counts
>>> a
'purple'
>>> b
'blue'
>>> c
'green'
Using the * operator in a function call or a list literal also relies on iteration.
So any iterable works with *.
Even something like a generator a file object:
>>> print(*fruits)
apple lemon pear watermelon
>>> [0, *coordinates, 9]
[0, 1, 8, 2, 9]
Layers on top of iteration
Lists aren’t just iterables.
We can also index lists:
>>> fruits[0]
'apple'
And get their length:
>>> len(fruits)
4
And we can modify them with append, pop, and other features.
Tuples are pretty much like lists, but they can’t be changed.
Objects that act like lists and tuples are called sequences. Lists are mutable sequences and tuples are immutable sequences.
Anything that has a length, can be indexed, and is iterable is a sequence.
What else seems like a sequence?
Strings and tuples are also sequences:
>>> greeting = "Hi y'all!"
>>> greeting[0]
'H'
>>> len(greeting)
9
Dictionaries are not sequences, but they do work with square brackets. Square brackets with a dictionary will lookup a value for a key instead of looking up a value for an index:
>>> counts["purple"]
3
Objects that act like dictionaries are called mappings.
Iterators
Sequences and mappings are common types of iterables, but they’re not the only types. Any object that can be looped over is an iterable… even objects that can only be looped over once.
For example, if we keep the file open and loop over it twice, we’ll see nothing the second time:
>>> file = open('my_file.txt')
>>> for line in file:
... print(line.strip())
...
First line in the file
Second line
Third and final line
>>> for line in file:
... print(line.strip())
...
>>> file.close()
Note that Python doesn’t store the whole file in memory as we loop over it. Instead it stores an 8 kilobyte buffer of lines and it replenishes that automatically as needed.
Files are iterators, which I like to call lazy iterables. Iterators do work as you loop them.
The built-in enumerate function also returns an iterator object.
>>> fruits = ['apple', 'lemon', 'pear', 'watermelon']
>>> e = enumerate(fruits)
>>> e
<enumerate object at 0x...>
Iterators can be passed to the built-in next function to get their next item:
>>> next(e)
(0, 'apple')
The next function only works on iterators:
>>> next(fruits)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not an iterator
Why?
Well, iterators are stateful in a way that iterables are not.
Iterators compute their next values as we loop over them. So if we start looping at this point, we’ll start up after that first value:
>>> list(e)
[(1, 'lemon'), (2, 'pear'), (3, 'watermelon')]
And if we loop over it again, we’ll get nothing at all:
>>> list(e)
[]
This iterator has been exhausted which means it has no more items left to compute. We’ve consumed every item it had.
There is no reset button for an iterator. They only go one direction and they don’t necessarily have any awareness of how many items they contain.
Calling next on an exhausted iterator raises a StopIteration exception:
>>> next(e)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
We could catch that exception:
>>> numbers = [2, 1, 3, 4, 7]
>>> big_numbers = (n for n in numbers if n > 100)
>>> try:
... first_big = next(big_numbers)
... except StopIteration:
... first_big = None
...
But the next function also accepts a default value to return, which we could use instead:
>>> big_numbers = (n for n in numbers if n > 100)
>>> first_big = next(big_numbers, None)
>>> print(first_big)
None
It’s even possible to make infinitely long iterators.
For example the count iterator in Python’s itertools module will count upward forever:
>>> from itertools import count
>>> for n in count():
... print(n)
...
0
1
2
...
Iterators are all over the place in Python.
The built-in zip and reversed functions also return iterators, as do many other looping helpers that you’ll find in the Python standard library and in third-party libraries:
>>> zip([3, 4, 5], [6, 7, 8])
<zip object at 0x...>
>>> reversed(fruits)
<list_reverseiterator object at 0x...>
How for loops work
Iterators also power all forms of iteration in Python.
Python’s for loops are actually powered by iterators.
This is a topic that you don’t need to understand deeply and we won’t dive into that today, but in case you’re curious, here’s what a for loop actually does under the hood…
This function:
def print_each(iterable):
for item in iterable:
print(item)
Is equivalent to this code:
def print_each(iterable):
iterator = iter(iterable)
while True:
try:
item = next(iterator)
except StopIteration:
break # Iterator exhausted: stop the loop
else:
print(item)
For more on this subject, watch Loop Better.
Generators
What if you wanted to make your own iterables that compute values as you loop over them?
Well, you can make your own iterator objects.
Technically you could do this by implementing a class with a __iter__ method and a __next__ method, like this:
class Squarer:
def __init__(self, iterable):
self.iterator = iter(iterable)
def __iter__(self):
return self
def __next__(self):
return next(self.iterator)**2
We can use that iterator class like this:
>>> numbers = [2, 1, 3, 4, 7]
>>> for n in Squarer(numbers):
... print(n)
...
4
1
9
16
49
But it’s usually much easier to make a generator function instead:
def square_all(iterable):
for n in iterable:
yield n**2
We can use the generator function like this:
>>> numbers = [2, 1, 3, 4, 7]
>>> for n in square_all(numbers):
... print(n)
...
4
1
9
16
49
Or, if the operation you’re performing is simple enough, you could make a generator expression instead:
numbers = [2, 1, 3, 4, 7]
squares = (n**2 for n in numbers)
We can loop over that squares object to get the same result as using the generator function:
>>> for n in squares:
... print(n)
...
4
1
9
16
49
Generator objects are a type of iterator. You can think of generators as the simplest way to implement an iterator in Python.
If you want to invent an iterable that lazily generates values as you loop over it, you can make your own custom iterator object with a generator function or a generator expression.
For more on generators, watch Lazy Looping.
Iterable Exercises
These exercises are all in the iterables.py file in the exercises directory. Edit the file to fix the error(s) in the function(s). To run the test: from the exercises folder, type python test.py <function_name>, like this:
$ python test.py parse_ranges
Starting with a vowel
The function get_vowel_names accepts a list of names and returns a new list containing all names that start with a vowel.
def get_vowel_names(names):
"""Return a list containing all names given that start with a vowel."""
vowel_names = []
for name in names:
if name[0].lower() in "aeiou":
vowel_names.append(name)
return vowel_names
Here’s an example usage:
>>> from iterables import get_vowel_names
>>> names = ["Alice", "Bob", "Christy", "Jules"]
>>> get_vowel_names(names)
['Alice']
>>> names = ["scott", "arthur", "jan", "elizabeth"]
>>> get_vowel_names(names)
['arthur', 'elizabeth']
Refactor this code to use a list comprehension. I recommend copy-pasting your way from a loop to a comprehension.
Parse Ranges
The function parse_ranges takes a string containing (inclusive) ranges of numbers and returns an iterable of those numbers.
The numeric ranges in the string will consist of two numbers separated by hyphens and each of the ranges will be separated by commas and any number of spaces.
It works like this:
>>> from iterables import parse_ranges
>>> for n in parse_ranges('1-2,4-4,8-13'):
... print(n)
1
2
4
8
9
10
11
12
13
>>> print(*parse_ranges('0-0, 4-8, 20-20, 43-45'))
0 4 5 6 7 8 20 43 44 45
Here's a solution for this version.
def parse_ranges(ranges_string):
"""Return iterable based on comma-separated numeric ranges."""
pairs = [
group.split('-')
for group in ranges_string.split(',')
]
numbers = [
num
for start, stop in pairs
for num in range(int(start), int(stop)+1)
]
return numbers
Now refactor it so that it returns a lazy iterator.
It should work like this:
>>> from iterables import parse_ranges
>>> numbers = parse_ranges('1-2,4-4')
>>> next(numbers)
1
>>> next(numbers)
2
>>> next(numbers)
4
>>> next(numbers)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
>>> numbers = parse_ranges('100-10000')
>>> next(numbers)
100
>>> next(numbers)
101
Interleave
The function interleave accepts two iterables and returns a list with the items in each iterable “interleaved” (item 0 from iterable 1, then item 0 from iterable 2, then item 1 from iterable 1, and so on). Assume the two lists have the same length.
def interleave(*iterables):
"""Return iterable of one item at a time from each given iterable."""
interleaved = []
for i in range(len(iterables[0])):
for iterable in iterables:
interleaved.append(iterable[i])
return interleaved
Refactor this code so that it works with any iterable (not just lists and sequences).
Example:
>>> from iterables import interleave
>>> from itertools import count, islice
>>> squares = (n**2 for n in count())
>>> list(islice(interleave(count(), squares), 10))
[0, 0, 1, 1, 2, 4, 3, 9, 4, 16]
Numeric Range
The numeric_range function accepts an iterable of numbers and computes their numeric range (the difference between the largest and smallest number).
The current implementation of this function does not work for any iterable:
def numeric_range(iterable):
"""Return difference between largest and smallest given numbers."""
return max(iterable) - min(iterable)
Refactor this function to work with any iterable.
>>> from iterables import numeric_range
>>> numeric_range([10, 8, 7, 5, 3, 6, 2])
8
>>> numeric_range({8, 7, 5, 3, 9, 6, 2})
7
>>> numeric_range(n**2 for n in range(4))
9
Infinite Interleave
Revisit interleave but make it work even with infinitely long iterables (the return value must be an iterator). To test this, comment out the @unittest.expectedFailure line in the iterables_test.py file, under class InterleaveTests.
Example:
>>> from iterables import interleave
>>> from itertools import count, islice
>>> squares = (n**2 for n in count())
>>> list(islice(interleave(count(), squares), 10))
[0, 0, 1, 1, 2, 4, 3, 9, 4, 16]
Head
The head accepts an iterable and a number n and returns the first n items from the iterable.
Currently this function accepts sequences, but not other types of iterables:
So these work:
>>> from iterables import head
>>> numbers = [2, 1, 3, 4, 7, 11]
>>> for n in head(numbers, 3):
... print(n)
...
2
1
3
>>> "".join(head('hello', 2))
'he'
>>> list(head('hello', 0))
[]
But this doesn’t work:
>>> head(enumerate('hello'), 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in head
TypeError: 'enumerate' object is not subscriptable
Here’s the current implementation of this function:
def head(iterable, n):
"""Return the first n items of given iterable."""
return iterable[:n]