Professional Documents
Culture Documents
The Repetition of A Process in Order To Generate A Sequence Example
The Repetition of A Process in Order To Generate A Sequence Example
The Repetition of A Process in Order To Generate A Sequence Example
What is an Iterator???
Any object that returns an iterator/pointer to iterate through its values is said
to be iterable
Example: List,Tuple,String
Example :
mylist=[1,2,3,4,5]
myiter=iter(mylist)
Now I will use the next() function to manually iterate through all the
values of the iterable
Print(next(myiter) 1
Print(next(myiter) 2
Print(next(myiter) 3
Print(next(myiter) 4
Print(next(myiter) 5
Print(next(myiter) error
or
print(myiter.__next__()) 1
print(myiter.__next__()) 2
print(myiter.__next__()) 3
print(myiter.__next__()) 4
print(myiter.__next__()) 5
print(myiter.__next__()) error
Yes………
The for loop first creates an iterator object and then executes the next() method
in an infinite while loop using Try block so as to terminate when the end of the
loop is reached
Iterator_object=iter(iterable)
While True:
try:
element=next(Iterator_object)
print(element)
except StopIteration:
break
Example
Create an iterator class that returns numbers starting with 1 and each
sequence will increase by one (returning 1,2,3,4,5 etc…)
class MyNumbers: 1
def __iter__(self): 2
self.a = 1
return self 3
4
def __next__(self):
5
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))