Skip to content

Commit 875eccb

Browse files
author
SanjayPradeeo
committed
Comparision between Generator and Nomal Iterator function
Comparision between Generator and Nomal Iterator function
1 parent 39e253f commit 875eccb

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
__author__ = 'Sanjay'
2+
3+
# Differences between Generator function and a Normal Iterator function
4+
5+
# Here is how a generator function differs from a normal function.
6+
#
7+
# Generator function contains one or more yield statement.
8+
9+
# When called, it returns an object (iterator) but does not start execution immediately.
10+
11+
# Methods like __iter__() and __next__() are implemented automatically. So we can iterate through the items using next().
12+
13+
# Once the function yields, the function is paused and the control is transferred to the caller.
14+
15+
# Local variables and their states are remembered between successive calls.
16+
17+
# Finally, when the function terminates, StopIteration is raised automatically on further calls.
18+
19+
20+
def my_gen():
21+
n = 1
22+
print('This is printed first')
23+
# Generator function contains yield statements
24+
yield n
25+
26+
n += 1
27+
print('This is printed second')
28+
yield n
29+
30+
n += 1
31+
print('This is printed at last')
32+
yield n
33+
34+
35+
a = my_gen()
36+
print (a)
37+
next(a) # This is printed first
38+
next(a) # This is printed second
39+
next(a) # This is printed at last
40+
41+
# next(a) # StopIteration because there's no more n value available to bring out.
42+
43+
# One interesting thing to note in the above example is that, the value of variable n is remembered between each call.
44+
#
45+
# Unlike normal functions, the local variables are not destroyed when the function yields. Furthermore, the generator object can be iterated only once.
46+
#
47+
# To restart the process we need to create another generator object using something like a = my_gen().
48+
49+
# Note: One final thing to note is that we can use generators with for loops directly.
50+
51+
# Here you go ..
52+
53+
for item in my_gen():
54+
print (item)
55+
56+
# Here's the output
57+
58+
# This is printed first
59+
# 1
60+
# This is printed second
61+
# 2
62+
# This is printed at last
63+
# 3

0 commit comments

Comments
 (0)