-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19.generators.py
More file actions
45 lines (31 loc) · 965 Bytes
/
19.generators.py
File metadata and controls
45 lines (31 loc) · 965 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# Example 1 : A simple generator function.
print('>>>> Example - 1 >>>>')
def my_generator():
n = 1
print('This is printed first')
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
my_gen = my_generator()
print('my_gen 1 : ', next(my_gen))
print('my_gen 2 : ', next(my_gen))
print('my_gen 3 : ', next(my_gen))
# Example 2 : Python Generator Expression.
print('\n')
print('>>>> Example - 2 >>>>')
my_list = [1, 3, 6, 10]
# square each term using list comprehension
list_ = [x ** 2 for x in my_list]
# same thing can be done using a generator expression
# generator expressions are surrounded by parenthesis ()
generator_ = (x ** 2 for x in my_list)
print('list_ :', list_)
print(generator_)
print('generator_ 1 : ', next(generator_))
print('generator_ 2 : ', next(generator_))
print('generator_ 3 : ', next(generator_))
print('generator_ 4 : ', next(generator_))