Here's another view using collections.abc
. This view may be useful the second time around or later.
From collections.abc
we can see the following hierarchy:
builtins.object
Iterable
Iterator
Generator
i.e. Generator is derived from Iterator is derived from Iterable is derived from the base object.
Hence,
[1, 2, 3]
and range(10)
are iterables, but not iterators. x = iter([1, 2, 3])
is an iterator and an iterable.iter()
on an iterator or a generator returns itself. Thus, if it
is an iterator, then iter(it) is it
is True.[2 * x for x in nums]
or a for loop like for x in nums:
, acts as though iter()
is called on the iterable (nums
) and then iterates over nums
using that iterator. Hence, all of the following are functionally equivalent (with, say, nums=[1, 2, 3]
):
for x in nums:
for x in iter(nums):
for x in iter(iter(nums))
:for x in iter(iter(iter(iter(iter(nums))))):