liveBook · Manning

Iterable

As explained in Python Workout: 50 ten-minute exercises

An iterable is a Python object that can provide its elements sequentially to an iteration process.

When a function or loop needs to process values one at a time, an iterable supplies those values sequentially. Lists, strings, tuples, dictionaries, sets, files, and range objects can serve as iterables; integers cannot. section 7.16 section 10.0

Use iterables in several common patterns:

  • Pass an iterable's elements as separate function arguments with unpacking: mysum(*[1, 2, 3]). section 1.8
  • Transform each element with a comprehension, whose source can be a string, list, tuple, dictionary, set, or file. section 7.16 section 7.2
  • Use iterables with built-ins such as enumerate, reversed, and range, or feed them into generator expressions. section 1.17 section 10.26

Transforming and consuming an iterable

numbers = range(15) print(','.join(str(number) for number in numbers)) Here, range supplies integers one at a time, the generator expression converts each integer to a string, and join combines the results. A list comprehension could also produce the intermediate values, but the generator expression feeds them directly to sum or join. section 7.2

class LoudIterator():
    def __init__(self, data):
        print('\tNow in __init__')
        self.data = data                        #1
        self.index = 0                          #2
 
    def __iter__(self):
        print('\tNow in __iter__')
        return self                             #3
 
    def __next__(self):
        print('\tNow in __next__')
        if self.index >= len(self.data):        #4
            print(
                f'\tself.index ({self.index}) is too big; exiting')
            raise StopIteration
 
        value = self.data[self.index]           #5
        self.index += 1                         #6
        print('\tGot value {value}, incremented index to {self.index}')
        return value
 
 
for one_item in LoudIterator('abc'):
    print(one_item)

A custom iterable follows the iterator protocol: __iter__ returns an iterator, __next__ supplies the next value, and StopIteration ends the loop. section 10.0 section 10.2

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Descends from everyday loops to __iter__, __next__, StopIteration, custom iterator classes, generators, and generator expressions.
Examples
Demonstrates lists, strings, dictionaries, files, range, comprehensions, argument unpacking, custom iterators, and hexadecimal conversion.
What it assumes
Assumes basic Python loops, functions, and collections while teaching the iterator protocol and custom iterable construction.
What you can do after
Build iterable classes, apply comprehensions and generator expressions, unpack iterable arguments, and distinguish iterable from non-iterable objects.
How it connects
Connects iterables with iterator protocol, iterators, generators, generator expressions, list comprehensions, enumerate, range, and itertools.

Also explained in

Compare how 7 books explain iterable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.