You are on page 1of 6

Programming using Python

prutor.ai Amey Karkare


Dept. of CSE
IIT Kanpur

For any queries reach out to rahulgr@iitk.ac.in or rahulgarg@robustresults.com


or whatsapp 9910043510

1
Python Programming
Source: https://docs.python.org/3/tutorial/classes.html#iterators
Iterators
• The backbone for for ... in
statement
for element in [1, 2, 3]:
print (element)

prutor.ai
for element in (1, 2, 3):
print (element)
for key in {'one':1, 'two':2}:
print (key)
for char in "123":
print (char)
for line in open("myfile.txt"):
print (line)
2
Iterators: Behind the Scene
• for statement calls iter() on the container object
• The iter() function returns an iterator object that

prutor.ai
defines the method next()
• next() accesses elements in the container one at
a time
• When there are no more elements, next() raises
a StopIteration exception
– tells the for loop to terminate.

3
prutor.ai
Iterators: Dissection

Source: https://docs.python.org/3/tutorial/classes.html#iterators
Create Your Own Iterator
• In a class, define an __iter__()
method which returns an object with

prutor.ai
a __next__() method.
• If the class defines __next__(), then
__iter__() can just return self

5
Source: https://docs.python.org/3/tutorial/classes.html#iterators
prutor.ai
>>> r = Reverse('spam')
>>> char = iter(r)
( ) >>> while(True)
... try:
... nxt = next(char)
Loosely equivalent to
... print(nxt)
... except StopIteration: 6
... break

You might also like