(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?
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.
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.
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.
That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With