Iterators provides a way to access elements of datastructures using concept of iterator. Iterator is a programming feature implemented for every datastructure which are iterable such as str,list,dictionary,tupple,set etc.
We can access elements in container without knowlege of internal datastructure. Iterator is an abstraction which is implemented by python by default. Same concept is available in languages like Java.
Example -
#This list has some elements which we want to acess one by one
l = [1,2,3,4]
for x in l:
print(x)
# list is a iterable - a datastructure
# it should have some iterator
# we can obtain iterator object using iter() method
# using iterator we can access elements one by one.
#if we need to iterate container, we can only use it once to access elements
Point to be noted, here for loop explictly implement the concept of iterator.
If we want to know how it is going, understand following sequence.
i) Get the iterator object by calling iter() function.
ii) In argument, required datastructure should be passed.
iii) when we apply iter(l) in case of list. Then an iterator object is returned. In actual, list class has a method which returns iterable object to iter method.
__iter__(self, /)
Implement iter(self).
iv) now we can store the iterator object in any reference and access elements using next method as
x = iter(l)
next(x) # provides first element
#This list has some elements which we want to acess one by one
l = [1,2,3,4]
x = iter(l) #gives iterator object
print(next(x)) #print 1
print(next(x)) #print 2
print(next(x)) #print 3
print(next(x)) #print 4
print(next(x)) # StopIteration Error
# list is a iterable - a datastructure
# it should have some iterator
# we can obtain iterator object using iter() method
# using iterator we can access elements one by one.
#if we need to iterate container, we can only use it once to access elements
next() method is builtin method, which provides next elements in iterable provided. It is unidirectional and can not be retraced.
Implementing same logic using while loop
#Implement same program using WHILE loop - NOT FOR
# This is how FOR loop abstraction is implemented
l = [1,2,3,4]
l = l[::-1] # reverse list
x = iter(l) #gives iterator object
n = len(l)
# while n:
# print(next(x))
# n = n-1
try:
while True:
print(next(x),end=' ')
except StopIteration:
pass
Generator
Generator is a special function and works exactly like iterator, but it yields something.
Generator always returns something and that is Generator object. Normal function doesn't use yield keyword and can return None example - print()
def f1():
yield 2
g = f1()
print(g)
Output
python -u "c:\Users\hsapkota\OneDrive\Python\A1.py"
<generator object f1 at 0x000001FEA6DC4930>
Generator object is an iterator
Example - In below program, we can see a generator object is returned which can be iterated and yielded values can be printed.
def f1():
yield 2
yield 3
yield 5
yield 7
yield 11
g = f1()
for e in g:
print(e)
It is useful for precise coding, we can create a generator object and use it to iterate elements one by one.
#program to print prime number
def f1(n):
for i in range(2,n+1):
for e in range(2,i):
if(i%e == 0 ):
break
else:
yield (i)
for x in f1(int(input("Enter the range : "))):
print(x,end=' ')
output
Enter the range : 50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Comments
Post a Comment