The documentation is badly worded. Here's the section you're referring to:
We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for
statement is such an iterator. The function list()
is another; it creates lists from iterables:
In this paragraph, iterator does not refer to a Python iterator object, but the general idea of "something which iterates over something". In particular, the for
statement cannot be an iterator object because it isn't an object at all; it's a language construct.
To answer your specific question:
... when we use this instruction:
list(zip(list1, list2))
are we using an iterator (list()
) to iterate through another iterator?
No, list()
is not an iterator. It's the constructor for the list
type. It can accept any iterable (including an iterator) as an argument, and uses that iterable to construct a list.
zip()
is an iterator function, that is, a function which returns an iterator. In your example, the iterator it returns is passed to list()
, which constructs a list
object from it.
A simple way to tell whether an object is an iterator is to call next()
with it, and see what happens:
>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> zipped = zip(list1, list2)
>>> zipped
<zip object at 0x7f27d9899688>
>>> next(zipped)
(1, 4)
In this case, the next element of zipped
is returned.
>>> list3 = list(zipped)
>>> list3
[(2, 5), (3, 6)]
Notice that only the last two elements of the iterator are found in list3
, because we already consumed the first one with next()
.
>>> next(list3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not an iterator
This doesn't work, because lists are not iterators.
>>> next(zipped)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
This time, although zipped
is an iterator, calling next()
with it raises StopIteration
because it's already been exhausted to construct list3
.