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

What are iterators and iterables?

  • All of them are iterables
  • A filehandle and the map object are also iterators. (Side note: You should always open files using the with statement and not like this.)
  • iter() would return the iterator from an iterable. We don't need this.
from collections.abc import Iterator, Iterable

a_string = "Hello World"
a_list   = ["Tiger", "Mouse"]
a_tuple  = ("Blue", "Red")
a_range  = range(10)
a_fh     = open(__file__)
a_map    = map(lambda x: x*2, a_list)

for thing in [a_string, a_list, a_tuple, a_range, a_map, a_fh]:
    print(thing.__class__.__name__)
    print(issubclass(thing.__class__, Iterator))
    print(issubclass(thing.__class__, Iterable))
    zorg = iter(thing)
    print(zorg.__class__.__name__)
    print(issubclass(zorg.__class__, Iterator))

    print()

a_fh.close()

Output:

str
False
True
str_iterator
True

list
False
True
list_iterator
True

tuple
False
True
tuple_iterator
True

range
False
True
range_iterator
True

TextIOWrapper
True
True
TextIOWrapper
True