0% found this document useful (0 votes)
48 views

PYTHON PROGRAMMING - Iterate

Iterators in Python are objects that can be used to iterate over iterable objects like lists, tuples, dictionaries, and files. An iterator must implement two methods: __iter__() which returns the iterator object itself, and __next__() which returns the next item in the iteration and raises a StopIteration error when finished. When a for loop iterates over an iterable, it uses the iter() method to get the iterator and next() to iterate through the items one by one until the end is reached.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

PYTHON PROGRAMMING - Iterate

Iterators in Python are objects that can be used to iterate over iterable objects like lists, tuples, dictionaries, and files. An iterator must implement two methods: __iter__() which returns the iterator object itself, and __next__() which returns the next item in the iteration and raises a StopIteration error when finished. When a for loop iterates over an iterable, it uses the iter() method to get the iterator and next() to iterate through the items one by one until the end is reached.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 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