Next / Previous / Contents / TCC Help System / NM Tech homepage

19.2. What is an iterable?

To iterate over a sequence means to visit each element of the sequence, and do some operation for each element.

In Python, we say that a value is an iterable when your program can iterate over it. In short, an iterable is a value that represents a sequence of one more values.

All instances of Python's sequence types are iterables. These types may be referred to as container types: a unicode string string is a container for 32-bit characters, and lists and tuples are general-purpose containers that can contain any sequence.

One of the most common uses for an iterable is in a for statement, where you want to perform some operation on a sequence of values. For example, if you have a tuple named celsiuses containing Celsius temperatures, and you want to print them with their Fahrenheit equivalents, and you have written a function cToF() that converts Celsius to Fahrenheit, this code does it:

>>> def cToF(c): return c*9.0/5.0 + 32.0
>>> celsiuses = (0, 20, 23.6, 100)
>>> for celsius in celsiuses:
...     print "{0:.1f} C = {1:.1f} F".format(celsius, cToF(celsius))
0.0 C = 32.0 F
20.0 C = 68.0 F
23.6 C = 74.5 F
100.0 C = 212.0 F

However, Python also supports mechanisms for lazy evaluation: a piece of program that acts like a sequence, but produces its contained values one at a time.

Keep in mind that the above code works exactly the same if celsiuses is an iterator (see Section 24.2, “Iterators: Values that can produce a sequence of values”). You may find many uses for iterators in your programs. For example, celsiuses might be a system that goes off and reads an actual thermometer and returns the readings every ten seconds. In this application, the code above doesn't care where celsiuses gets the values, it cares only about how to convert and print them.