27
loading...
This website collects cookies to deliver better user experience
iter()
. When we provide an iterable as an argument to the iter()
function ( which in returns call the __iter__()
dunder method on the object ), it returns something called iterator.>>> guests = {'Luffy', 'Zorro', 'Sanji'}
>>> iter(guests)
<set_iterator object at 0x7f7983d1dab0>
next()
on the iterator object, it returns the stream's next items.>>> guests = {'Luffy', 'Zorro', 'Sanji'}
>>> guest_iterator = iter(guests)
>>> next(guest_iterator)
'Zorro' # Sets are unordered
>>> next(guest_iterator)
'Luffy'
>>> next(guest_iterator)
'Sanji'
>>> next(guest_iterator) # No more items left in the set
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
iter()
and next()
functions.__iter__()
defined. It's the __iter__()
method, which returns an iterator from an iterable.sequences
, sets
, and dictionaries
have the dunder method __iter__()
defined, which lets us use in for
loop.while
loop to iterate over a set of objects.>>> guests = {'Luffy', 'Zorro', 'Sanji'}
>>> guest_iterator = iter(guests) # Same as guests.__iter__()
>>> while True:
... try:
# Same as guest_iterator.__next__()
... guest = next(guest_iterator)
... print(guest)
... except StopIteration as e:
... break
Zorro
Luffy
Sanji
while
loop we wrote is pretty close to what happens under the hood when we iterate on an iterable using a for
loop. Although, when using iterables with the for loop, we don't need to call the iter()
function or handle the StopIteration
error as the for statement does that automatically for us.iter()
function or the dunder method <iterable>.__iter__()
.
Call the built-in function next()
or the dunder method <iterator>.__next__()
on the iterator object.for
blockStopIteration
__iter__()
method defined that returns an iterator.__iter__()
method and a __next__()
method.