8

(For python 3)

In the python docs, you can see that the list() function takes an iterable.

In the python docs, you can also see that the next() funciton takes an iterator.

So I did this in IDLE:

>>> var = map(lambda x: x+5, [1,2,3])
>>> var
>>> next(v)
>>> list(v)

Which gives the output:

<map object at 0x000000000375F978>
6
[7,8]

Frankly, this isn't what I expected. Is a map object an iterator or an iterable? Is there even a difference? Clearly both the list() and next() functions work on the map object, whatever it is.

Why do they both work?

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220

1 Answers1

23

An iterator is an iterable, but an iterable is not necessarily an iterator.

An iterable is anything that has an __iter__ method defined - e.g. lists and tuples, as well as iterators.

Iterators are a subset of iterables whose values cannot all be accessed at the same time, as they are not all stored in memory at once. These can be generated using functions like map, filter and iter, as well as functions using yield.

In your example, map returns an iterator, which is also an iterable, which is why both functions work with it. However, if we take a list for instance:

>>> lst = [1, 2, 3]
>>> list(lst)
[1, 2, 3]
>>> next(lst)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    next(lst)
TypeError: 'list' object is not an iterator

we can see that next complains, because the list, an iterable, is not an iterator.

Volatility
  • 31,232
  • 10
  • 80
  • 89
  • 10
    "Iterators are a subset of iterables whose values cannot all be accessed at the same time, as they are not all stored in memory at once": this is completely incorrect. For example, if you are reading this before 2025, the values of python 3's `range(1000000000000000000)` iterable cannot fit in your laptop's memory. And yet, this iterable is *not* an iterator. The correct definition is "Iterators are a subset of iterables that have `next` method." – max Apr 28 '19 at 06:51