-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbasic.py
More file actions
39 lines (30 loc) · 770 Bytes
/
basic.py
File metadata and controls
39 lines (30 loc) · 770 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
"""
Demonstrates use cases of generators
"""
import time
def compute():
for x in range(5):
time.sleep(.5)
yield x
# directly calling a function implementing yield inside will return generator object
genObject = compute()
print(genObject) # prints generator object
# generator individual iterate
print('\nIterate as next(genObject)')
while True:
try:
print(next(genObject))
except StopIteration:
break
# generator methods can be iterated over
print('\nIterate using for in loop')
for n in compute():
print(n)
# get iterator of generator and iterate over
print('\nIterate using iter(genObject)')
iterator = iter(compute())
while True:
try:
print(next(iterator))
except StopIteration:
break