liveBook · Manning

Iterable

As explained in Python Workout, Second Edition

An iterable is a Python object that can provide its elements one at a time for iteration.

An iterable is an object that can provide elements one at a time. You can place it in a for loop, pass it to many functions, or use it as the source of a comprehension. section 11.1 section 11.5

Common iterable operations include:

  • Iterate through strings, lists, tuples, dictionaries, files, ranges, and other supported objects without manually tracking indexes. section 11.2 section 11.5
  • Transform an iterable into a list with a comprehension; use a traditional for loop when the goal is only to perform an action. section 8.2 section 8.3
  • Unpack an iterable into separate function arguments by placing * before it in the call. section 2.7
  • Distinguish an iterable from an iterator: an iterable supplies an iterator through __iter__, while an iterator supplies values through __next__. section 11.5

A for loop calls iter on its target, repeatedly calls next on the returned iterator, and stops when StopIteration is raised. This protocol lets different objects yield characters, keys, lines, or other values according to their own behavior. section 11.2

Joining numbers from an iterable

Convert each number while iterating, then join the resulting strings: numbers = range(15) print(','.join(str(number) for number in numbers)) The generator expression consumes numbers one at a time and avoids passing integers directly to str.join. section 8.3

Table 11.1 What you need to know
Concept
What is it?
Example
To learn more
iter
A built-in function that returns an object’s iterator
iter('abcd')
next
A built-in function that requests the next object from an iterator
next(i)
StopIteration
An exception raised to indicate the end of a loop
raise StopIteration
enumerate
Helps us to number elements of iterables
for i, c in enumerate('ab'):
print(f'{i}: {c}')
Iterables
A category of data in Python
Iterables can be put in for loops or passed to many functions.
itertools
A module with many classes for implementing iterables
import itertools
range
Returns an iterable sequence of integers
# every 3rd integer, from 10
# to (not including) 50
range(10, 50, 3)
os.listdir
Returns a list of files in a directory
os.listdir('/etc/')
os.walk
Iterates over the files in a directory
os.walk('/etc/')
yield
Returns control to the loop temporarily, optionally returning a value
yield 5
os.path.join
Returns a string based on the path components
os.path.join('etc', 'passwd')
time.perf_
counter
Returns the number of elapsed seconds (as a float) since the program was started
time.perf_counter()
zip
Takes n iterables as arguments and returns an iterator of tuples of length n
# returns [('a', 10),
# ('b', 20), ('c', 30)]
zip('abc',
[10, 20, 30])

Use the reference table to navigate iter, next, StopIteration, enumerate, iterables, itertools, and range. section 11.5

How Python Workout, Second Edition covers it

How deep it goes
Defines the iterator protocol and distinguishes iterables from iterators, while deferring deeper protocol practice to custom iterators and generators.
Examples
Demonstrates strings, lists, dictionaries, files, ranges, numeric joining, hexadecimal conversion, comprehensions, and custom enumeration.
What it assumes
Assumes familiarity with for loops and comprehensions while teaching the iterator protocol and iterable-versus-iterator distinction explicitly.
What you can do after
Build iterable classes and generator functions, then diagnose for-loop behavior through __iter__, __next__, and StopIteration.
How it connects
Connects iterables with for loops, iterators, comprehensions, generator expressions, generators, map, filter, enumerate, and argument unpacking.

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, Second Edition. The section links point to the parts of the book it draws on.