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

range is iterable but it is not an iterator

Just as a string or a list, the range function in Python is also an "iterable" but it is not an "iterator". In many aspects it behaves as an iterator. Specifically it allows us to iterate over numbers. Range Is Not An Iterator

for n in range(2, 12, 3):
    print(n)
print()

for n in range(3):
    print(n)
print()

for n in range(2, 5):
    print(n)
print()

from collections.abc import Iterator, Iterable
rng = range(2, 5)
print(issubclass(rng.__class__, Iterator))
print(issubclass(rng.__class__, Iterable))

Output:

2
5
8
11

0
1
2

2
3
4

False
True