You are on page 1of 10

PYTHON

PROGRAMMING

TOPIC: ITERATORS

G. MAHALAKSHMI MALINI,
ASSISTANT PROFESSOR/ECE
SCHOOL OF ENGINEERING,
AVINASHILINGAM INSTITUTE FOR HOME SCIENCE AND
HIGHER EDUCATION FOR WOMEN
ITERABLE:

– In python, an object which implements the


__iter__() method is called an iterable.
ITERATORS

– Iterator in python is simply an object that can


return data one at a time while iterating over it.
– For an object to be an iterator, it must implement
two methods:
 Iter
 next
__iter(iterable):

– It is called for the initialization of an iterator. This


returns an iterator object.
Next(__next__):

– The next method returns the next value for the iterable.

– When we use a for loop to transverse any iterable object,


internally it uses the iter() method to get an iterator object which
further uses next() method to iterate over.

– This method raises a stop iteration to signal the end of the


iteration.
PROGRAM 1:

numbers=[1,4,9]
value=numbers.__iter__()
item1=value.__next__()
print(item1)
item2=value.__next__()
print(item2)
item3=value.__next__()
print(item3)
OUTPUT 1

– 1
– 4
– 9
PROGRAM 2:

– iterable_value = 'Geeks'
– iterable_obj = iter(iterable_value)

– while True:
– try:

– # Iterate by calling next
– item = next(iterable_obj)
– print(item)
– except StopIteration:

– # exception will happen when iteration will over
– break
OUTPUT 2:

– G
– e
– e
– k
– s
THANK YOU

You might also like