Skip to content

Commit 06e3e6f

Browse files
committed
Add samplegenerators.py
1 parent 9b2d54e commit 06e3e6f

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

samplegenerators.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Generators hold values that are fetched lazily.
2+
# Meaning that the entire collection isn't stored
3+
# in memory all at once, but rather retrieved when
4+
# needed.
5+
6+
# This is best used when dealing with a large
7+
# collection of items. Such as rows returned from
8+
# a database call or looping over a large csv.
9+
10+
# Generators are intelligent enough to handle these
11+
# large collections without running out of memory.
12+
# They dispose of variables in memory that are no
13+
# longer used and do not worry about variables
14+
# that are not yet needed.
15+
16+
# Here's the syntax for a generator. It's just a
17+
# function! Take note of the yield keyword. yield
18+
# basically means 'return', but lets Python know
19+
# we'll be coming back for more.
20+
def color_generator():
21+
yield 'blue'
22+
yield 'orange'
23+
yield 'yellow'
24+
yield 'purple'
25+
26+
# One way to use generators is by calling `next()`
27+
# on it's instance
28+
g = color_generator() # create the instance
29+
next(g) # 'blue'
30+
next(g) # 'orange'
31+
next(g) # 'yellow'
32+
next(g) # 'purple'
33+
34+
# However, once a generator is exhausted, it will
35+
# not start back at the beginning.
36+
next(g) # Raises StopIteration error.
37+
38+
# They're also iterables. No StopIteration errors
39+
# are thrown with this method.
40+
for color in color_generator():
41+
print(color)
42+
43+
# 'blue'
44+
# 'orange'
45+
# 'yellow'
46+
# 'purple'
47+

0 commit comments

Comments
 (0)