You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# 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
+
defmy_gen():
21
+
n=1
22
+
print('This is printed first')
23
+
# Generator function contains yield statements
24
+
yieldn
25
+
26
+
n+=1
27
+
print('This is printed second')
28
+
yieldn
29
+
30
+
n+=1
31
+
print('This is printed at last')
32
+
yieldn
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.
0 commit comments