Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator vs Iterable?

(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?

like image 978
temporary_user_name Avatar asked Sep 15 '13 06:09

temporary_user_name


People also ask

Is an iterator always iterable?

Iterators are also Iterables. We can get an iterator from an iterable by calling iter() function. Similarly, we can call iter() function on the iterator itself.

What is the difference between the Iterable interface and the iterator interface?

Implementing Iterable interface allows an object to be the target of the "foreach" statement. Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.

What is the difference between iterator and for loop in Python?

The main difference between Iterator and the classic for loop, apart from the obvious one of having or not having access to the index of the item you're iterating, is that using Iterator abstracts the client code from the underlying collection implementation, allow me to elaborate.

Is iterator faster than for loop Python?

That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.


1 Answers

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.

like image 50
Volatility Avatar answered Oct 14 '22 07:10

Volatility