Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Iterators (Iterables)

You already know that there are all kinds of objects in Python that you can iterate over using the for-in construct. For example, you can iterate over the characters of a string, or the elements of a list, or whatever range() returns. You can also iterate over the lines of a file and you have probably seen the for in construct in other cases as well. The objects that can be iterated over are collectively called iterables. You can do all kind of interesting things on such iterables. We'll see a few now.

  • There are several data types that we can iterate over using the for ... in ... construct. For example, strings, lists, tuples, filehandles, and range:

string

We can iterate over the "elements" of a string that are the characters. We can also print the whole string.

name = "Learn 🐍 Python"
for cr in name:
    print(cr)
print(name)

Output:

L
e
a
r
n
 
🐍
 
P
y
t
h
o
n
Learn 🐍 Python

list

We can iterate over the elements of a list. We can also print the whole list at once.


numbers = [101, 2, 3, 42]
for num in numbers:
    print(num)
print(numbers)

Output:

101
2
3
42
[101, 2, 3, 42]

tuple

We can iterate over the elements of a tuple. We can also print the whole tuple at once.


planets = ("Mars", "Earth", "Venus")
for planet in planets:
    print(planet)
print(planets)

Output:

Mars
Earth
Venus
('Mars', 'Earth', 'Venus')

filehandle

We can iterate over a filehandle. On each iteration we'll get one line from the file.

import sys

file = sys.argv[0]

with open(file) as fh:
    for row in fh:
        print(row, end="")

Running this program will print itself.

We can also print the filehandle: print(fh), but the output will be:

<_io.TextIOWrapper name='iterable_fh.py' mode='r' encoding='UTF-8'>

not the content of the file.

So the "thing" that the open function returned is iterable, but it is different from the previous 3 types.

range

The range function returns something, we can use the for-in loop to iterate over it and we'll get back the expected numbers.

However, if we print the value that we got back from the range function it looks strange. It is the range object.

Unlike in Python 2, here in Python 3 the range function does not return a list of numbers. It returns an object that allows us to iterate over the numbers, but it does not hold the numbers.


rng = range(3, 9, 2)
for num in rng:
    print(num)
print(rng)

Output:

3
5
7
range(3, 9, 2)

range is interesting. We are going to take a closer look in the next few pages.