Skip to content

Commit 9ea8ec6

Browse files
committed
Adding yield
1 parent c56a142 commit 9ea8ec6

File tree

4 files changed

+43
-0
lines changed

4 files changed

+43
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
- [Format](python_utils/format/README.md)
5555
- [List Comprehension](https://htmlpreview.github.io/?https://github.com/andrelbd1/algorithms-practice/blob/master/python_utils/list_comprehension/list_comprehension.html)
5656
- [Walrus Operator](python_utils/walrus_operator/README.md)
57+
- [Yield](python_utils/yield/README.md)
5758

5859
### [Design Patterns](https://www.youtube.com/playlist?list=PLQhuS49baMUmiygUlBJexyHxpSghlId7g)
5960
- [Singleton](design_patterns/singleton/README.md)

python_utils/yield/README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
### Yield
2+
- Yield is a fairly simple statement. Its primary job is to control the flow of a generator function in a way that’s similar to return statements.
3+
- When you call a generator function or use a generator expression, you return a special iterator called a generator. You can assign this generator to a variable in order to use it. When you call special methods on the generator, such as next(), the code within the function is executed up to yield.
4+
- When the Python yield statement is hit, the program suspends function execution and returns the yielded value to the caller. When a function is suspended, the state of that function is saved. This includes any variable bindings local to the generator, the instruction pointer, the internal stack, and any exception handling.
5+
6+
7+
#### Examples
8+
- [Code 1](example_1.py)
9+
- [Code 2](example_2.py)
10+
11+
12+
### [Back](../../README.md)

python_utils/yield/example_1.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
def random_numbers():
2+
for i in range(10):
3+
yield i
4+
5+
gen = random_numbers()
6+
7+
print(next(gen))
8+
print(next(gen))
9+
print(next(gen))
10+
print(next(gen))
11+
print(list(gen))

python_utils/yield/example_2.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def random_numbers():
2+
for i in range(3):
3+
yield i
4+
5+
def random_numbers_100():
6+
for i in range(100,105):
7+
yield i
8+
9+
def generator():
10+
yield from random_numbers()
11+
print('Next generator')
12+
yield from random_numbers_100()
13+
14+
if __name__ == '__main__':
15+
gen = generator()
16+
print(next(gen))
17+
print(next(gen))
18+
print(next(gen))
19+
print(list(gen))

0 commit comments

Comments
 (0)