#################################################
## Uses of Generators:
## 1) It will automatically takes care of __iter__() and next()/__next__()
## 2) More easy to use
## 3) It won't load everything in memory, so it consumes less memory (memory efficient)
#################################################
def generatorFunction(listA):
for each in listA:
yield each
print '------'
ic = generatorFunction(['A','B','C'])
for each in ic:
print(each)
## Uses of Generators:
## 1) It will automatically takes care of __iter__() and next()/__next__()
## 2) More easy to use
## 3) It won't load everything in memory, so it consumes less memory (memory efficient)
#################################################
def generatorFunction(listA):
for each in listA:
yield each
print '------'
ic = generatorFunction(['A','B','C'])
for each in ic:
print(each)
print '------'
ic = generatorFunction(['A','B','C'])
print (ic)
print(next(ic))
print(next(ic))
print(next(ic))
#print(next(ic)) #This raises StopIteration
print (ic)
ic = generatorFunction(['A','B','C'])
print (ic)
print(next(ic))
print(next(ic))
print(next(ic))
#print(next(ic)) #This raises StopIteration
print (ic)
print '$$$$$$$$'
# This will not print anything, since generator got exhausted as we earlier called next() many times already
# You have to re-initialize generator object again
for each in ic:
print(each)
ic = generatorFunction(['A','B','C'])
print '#########'
# This will not print anything, since generator got exhausted as we earlier called next() many times already
# You have to re-initialize generator object again
for each in ic:
print(each)
ic = generatorFunction(['A','B','C'])
print '#########'
for each in ic:
print(each)
Output:
Output:
------
A
B
C
------
<generator object generatorFunction at 0x7f82ddcaca50>
A
B
C
<generator object generatorFunction at 0x7f82ddcaca50>
--$$$$$----
--#####----
A
B
C
No comments:
Post a Comment