You have used for hundreds of times, but what really happens when you write for x in items? Understanding it is the basis of generators.
Iterable: something that can be looped over
An iterable is any object that can be looped over with a for: lists, tuples, texts, dictionaries, sets, range, files…
for letter in "sun":
print(letter)
# s
# u
# n
Iterator: the one that remembers where you are
An iterator is an object that produces the elements one at a time and remembers where it left off. It is obtained with iter() and advanced with next():
colors = ["red", "green", "blue"]
it = iter(colors)
print(next(it)) # red
print(next(it)) # green
print(next(it)) # blue
When there are no more elements, next raises the StopIteration exception:
it = iter([1, 2])
print(next(it)) # 1
print(next(it)) # 2
try:
print(next(it))
except StopIteration:
print("No more left") # No more left
With next(it, value) you can give a default value instead of receiving the exception:
it = iter([1])
print(next(it, "end")) # 1
print(next(it, "end")) # end
What a for really does
A for loop is a convenient way of writing the following:
items = ["a", "b"]
# for x in items: print(x) is equivalent to:
it = iter(items)
while True:
try:
x = next(it)
except StopIteration:
break
print(x)
# a
# b
Practice with Looping with iter and next.
Iterable versus iterator
| Iterable | Iterator | |
|---|---|---|
| Examples | List, text, dictionary, range | The result of iter(...), a generator |
| Can be looped over several times | Yes | No: it runs out |
| Obtained with | Directly | iter(iterable) |
Supports next() | No | Yes |
An iterator is exhausted: once it has been traversed, it cannot be used again:
it = iter([1, 2, 3])
print(list(it)) # [1, 2, 3]
print(list(it)) # [] (it has already been consumed)
Things that were already iterators
Many functions you already know return iterators, not lists. That is why you have to wrap them with list() to see their content:
print(map(str, [1, 2])) # <map object at 0x...>
print(list(map(str, [1, 2]))) # ['1', '2']
print(list(zip("ab", [1, 2]))) # [('a', 1), ('b', 2)]
print(list(enumerate("ab"))) # [(0, 'a'), (1, 'b')]
An iterator does not calculate all the values at once, but one at a time, when they are requested. This is called lazy evaluation, and it is the central idea of this lesson.