Python Iterators Examples
Short, runnable programs that show python iterators in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Iterators lesson.
1Iterable or iterator? Ask iter()
An iterator returns itself when you call iter() on it, while an ordinary iterable gives you a new object. That one test tells the two apart.
things = {
"list": [1, 2, 3],
"string": "abc",
"dict": {"a": 1},
"list iterator": iter([1, 2, 3]),
}
for label, thing in things.items():
print(label, "->", iter(thing) is thing)Expected outputlist -> False
string -> False
dict -> False
list iterator -> True
2Skipping a header line with next()
The first next() takes the header off the iterator. The for loop then continues with the rows that remain, because it shares the same iterator.
lines = iter([
"item,qty,price",
"pen,3,1.50",
"notebook,2,4.00",
"stapler,1,9.25",
])
header = next(lines)
total = 0
for line in lines:
item, qty, price = line.split(",")
total += int(qty) * float(price)
print("Columns:", header.split(","))
print("Order total:", total)Expected outputColumns: ['item', 'qty', 'price']
Order total: 21.75
3Reading in chunks with iter(function, sentinel)
partial(message.read, 8) makes a function that reads 8 characters each time it is called. iter() keeps calling it until it returns the empty string, which means the text has ended.
import io
from functools import partial
message = io.StringIO("Meet at the north gate at noon")
for chunk in iter(partial(message.read, 8), ""):
print(repr(chunk))Expected output'Meet at '
'the nort'
'h gate a'
't noon'
4A reusable iterable class
Order has no __next__. Its __iter__ returns a fresh iterator over the list, so len(list(...)), enumerate, in and sorted can all read it, one after the other.
class Order:
def __init__(self, *items):
self.items = list(items)
def __iter__(self):
return iter(self.items)
order = Order("pen", "ink", "paper")
print(len(list(order)), "items")
for number, item in enumerate(order, start=1):
print(number, item)
print("ink" in order)
print(sorted(order))Expected output3 items
1 pen
2 ink
3 paper
True
['ink', 'paper', 'pen']
5An endless iterator that remembers its place
InvoiceNumbers never raises StopIteration, so it could go on forever. zip stops when the shorter list labels runs out, and the iterator simply continues from where it was left.
class InvoiceNumbers:
def __init__(self, prefix, start=1):
self.prefix = prefix
self.number = start
def __iter__(self):
return self
def __next__(self):
label = f"{self.prefix}-{self.number:04d}"
self.number += 1
return label
invoices = InvoiceNumbers("INV", start=41)
print(next(invoices))
print(next(invoices))
for client, number in zip(["Asha", "Ben", "Chen"], invoices):
print(client, number)
print(next(invoices))Expected outputINV-0041
INV-0042
Asha INV-0043
Ben INV-0044
Chen INV-0045
INV-0046
6Readers use items up: unpacking and in
Starred unpacking drains the iterator completely, so the later sum() finds nothing. Searching with in stops at the match, and everything it passed is gone too.
readings = iter([18, 22, 19, 25, 21])
first, second, *others = readings
print(first, second, others)
print(sum(readings))
numbers = iter([5, 8, 12, 20])
print(8 in numbers)
print(list(numbers))Expected output18 22 [19, 25, 21]
0
True
[12, 20]
Practise next
Python Iterators exercises → Back to the lesson
Python for Loops examplesPython enumerate() and zip() examplesPython Generators, Iterators and yield examplesPython map, filter and reduce examples