-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path47_Yield.py
More file actions
58 lines (45 loc) · 1.17 KB
/
47_Yield.py
File metadata and controls
58 lines (45 loc) · 1.17 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
"""Yield keyword is used to create generators, which are special types of iterators that allow values to be produced lazily, one at a time, instead of returning them all at once."""
# Syntax
# def generator_function():
# yield value
"""Examples of yield"""
# Example 1: Simple Generator to Yield Numbers Sequentially
def fun(m):
for i in range(m):
yield i
# call the generator function
for n in fun(5):
print(n)
# Example 2: Generator functions and yield
def my_generator():
yield "Hello world!!"
yield "GeeksForGeeks"
g = my_generator()
print(type(g))
print(next(g))
print(next(g))
# Example 3: Generating an Infinite Sequence
def infinite_sequence():
n = 0
while True:
yield n
n += 1
g = infinite_sequence()
for _ in range(10):
print(next(g), end=" ")
# Example 4: Extracting even numbers from list
def fun(a):
for n in a:
if n % 2 == 0:
yield n
a = [1, 4, 5, 6, 7]
print(list(fun(a)))
# Example 5: Using yield as a boolean expression
def fun(text, keyword):
w = text.split()
for n in w:
if n == keyword:
yield True
txt = "geeks for geeks"
s = fun(txt, "geeks")
print(sum(s))