Iterators in Python are used to
iterate over a group of elements, containers, like list. For a container to
support iterator, it must provide __iter__().
container.__iter__() :
This returns an iterator object.
container.__iter__() :
This returns an iterator object.
Iterator
protocol:
The iterator object is required to
support the iterator protocol. Iterator protocol is implemented by an iterator
object by providing definition of the following 2 functions:
1. iterator.__iter__() :
It returns the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements.
2. iterator.__next__() :
It returns the next item from the container. If there are no further items, raise the StopIteration exception.
1. iterator.__iter__() :
It returns the iterator object itself. This is required to allow both containers and iterators to be used with the for and in statements.
2. iterator.__next__() :
It returns the next item from the container. If there are no further items, raise the StopIteration exception.
Example
of iterator on list:
>>>
a=[1,2,3]
>>> i1= a.__iter__() # creating an iterator using __iter__() on container
>>> i1
<listiterator object at 0x7f5192ccbd10>
>>> i2= iter(a) # creating another iterator using iter() which calls __iter__() on container
>>> i2
<listiterator object at 0x7f5192ccbcd0>
>>> i1.next()
1
>>> next(i1) # calls i1.next()
2
>>> next(i2)
1
>>> i1= a.__iter__() # creating an iterator using __iter__() on container
>>> i1
<listiterator object at 0x7f5192ccbd10>
>>> i2= iter(a) # creating another iterator using iter() which calls __iter__() on container
>>> i2
<listiterator object at 0x7f5192ccbcd0>
>>> i1.next()
1
>>> next(i1) # calls i1.next()
2
>>> next(i2)
1
Iterators are required to implement
__iter__ which returns the iterator (self) . Hence it can be used with for
in
>>> for x
in i1:
... print x
...
3
... print x
...
3
No comments:
Post a Comment