Python Generators PDF
Python Generators PDF
Complete
Python
In
Simple Way
1 https://www.youtube.com/durgasoftware
GENERATOR
FUNCTIONS
STUDY MATERIAL
2 https://www.youtube.com/durgasoftware
Generator is a function which is responsible to generate a sequence of values.
We can write generator functions just like ordinary functions, but it uses yield keyword to
return values.
yield
1) def mygen():
2) yield 'A'
3) yield 'B'
4) yield 'C'
5)
6) g=mygen()
7) print(type(g))
8)
9) print(next(g))
10) print(next(g))
11) print(next(g))
12) print(next(g))
Output
<class 'generator'>
A
B
C
Traceback (most recent call last):
File "test.py", line 12, in <module>
print(next(g))
StopIteration
1) def countdown(num):
2) print("Start Countdown")
3) while(num>0):
4) yield num
5) num=num-1
6) values=countdown(5)
7) for x in values:
8) print(x)
3 https://www.youtube.com/durgasoftware
Output
Start Countdown
5
4
3
2
1
1) def firstn(num):
2) n=1
3) while n<=num:
4) yield n
5) n=n+1
6)
7) values=firstn(5)
8) for x in values:
9) print(x)
Output
1
2
3
4
5
Eg: 0,1,1,2,3,5,8,13,21,...
1) def fib():
2) a,b=0,1
3) while True:
4) yield a
5) a,b=b,a+b
6) for f in fib():
4 https://www.youtube.com/durgasoftware
7) if f>100:
8) break
9) print(f)
Output
0
1
1
2
3
5
8
13
21
34
55
89
5 https://www.youtube.com/durgasoftware
17)
18) def people_generator(num_people):
19) for i in range(num_people):
20) person = {
21) 'id':i,
22) 'name': random.choice(names),
23) 'major':random.choice(subjects)
24) }
25) yield person
26)
27) '''''t1 = time.clock()
28) people = people_list(10000000)
29) t2 = time.clock()'''
30)
31) t1 = time.clock()
32) people = people_generator(10000000)
33) t2 = time.clock()
34)
35) print('Took {}'.format(t2-t1))
Note: In the above program observe the differnce wrt execution time by using list and
generators
We will get MemoryError in this case because all these values are required to store in the
memory.
Generators:
g=(x*x for x in range(10000000000000000))
print(next(g))
Output: 0
We won't get any MemoryError because the values won't be stored at the beginning
6 https://www.youtube.com/durgasoftware