Day 35 Of 100DayOfCode: More About Python Iterator And Generator
Durga Pokharel
Posted on January 28, 2021
Today is my 35 day of #100DaysOfCode and #Python. Like yesterday today also continue to learn about web access on python, Database using python, complete some assignment.
Also learned more about python iterator and python generator. Tried to write some code on python iterator.
Code On Python Iterator And Generator
We know that python generator is like a python function. There are no more different in both. Instead of return statement we used yield statement in python generator. There are many advantage of python generator over python function but I know one is python function return statement terminates a function entirely but in generators yield statement pauses the function saving all its states and later continue from there on successive calls. Here is some code,
def Integers():
i = 1
while True:
yield i
i = i + 1
def fibonacci_number(n):
a = 0
b = 1
fib = [ a,b]
for i in range(n):
f = a+b
a = b
b = f
fib.append(f)
yield fib
def take(n , fibo):
seq = iter(fibo)
result = []
try:
for i in range(n):
result.append(next(fibo))
except StopIteration:
pass
return result
print(take(10, fibonacci_number(10)))
When above code run we can get following output,
[[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]]
Here is another example
import string
print("List Iteration")
def fibonacci_number(n):
a = 0
b = 1
fib = [ a,b]
for i in range(n):
f = a+b
a = b
b = f
fib.append(f)
return fib
print(fibonacci_number(10))
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
d = {'a':10, 'b':1, 'c':22}
l = list()
for key, val in d.items() :
l.append( (val, key) )
l.sort(reverse=True)
print(l)
# Iterating over a String
print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)
# Iterating over dictionary
print("\nDictionary Iteration")
fhand = open('mbox-short.txt')
counts = dict()
for line in fhand:
words = line.split()
for word in words:
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
lst = list()
for key,val in counts.items():
lst.append((val,key))
lst.sort(reverse = True)
for key,val in lst[:10]:
print(key,val)
When we run above code we get following output.
List Iteration
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Tuple Iteration
[(22, 'c'), (10, 'a'), (1, 'b')]
String Iteration
G
e
e
k
s
Dictionary Iteration
352 Jan
324 2008
245 by
243 Received:
219 -0500
218 from
203 4
194 with
183 Fri,
136 id
Day 35 Of #100DaysOfCode and #Python
— Durga Pokharel (@mathdurga) January 28, 2021
* More About Database Using Python
* More About Web Access on Python
* Python Iterator And Generator #100DaysOfCode ,#CodeNewbie ,#beginner pic.twitter.com/26KaNpEbzk
Posted on January 28, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.