Day 35 Of 100DayOfCode: More About Python Iterator And Generator
Tags: 100daysofcode, codenewbie, beginners, python
Published: 2021-01-28 15:05:35

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,


```python
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,

```python
[[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]]
```
Here is another example 
```python
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.

```python
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
```

<blockquote class="twitter-tweet"><p lang="en" dir="ltr">Day 35 Of <a href="https://twitter.com/hashtag/100DaysOfCode?src=hash&amp;ref_src=twsrc%5Etfw">#100DaysOfCode</a> and <a href="https://twitter.com/hashtag/Python?src=hash&amp;ref_src=twsrc%5Etfw">#Python</a> <br>* More About Database Using Python<br>* More About Web Access on Python<br>* Python Iterator And Generator <a href="https://twitter.com/hashtag/100DaysOfCode?src=hash&amp;ref_src=twsrc%5Etfw">#100DaysOfCode</a> ,<a href="https://twitter.com/hashtag/CodeNewbie?src=hash&amp;ref_src=twsrc%5Etfw">#CodeNewbie</a> ,<a href="https://twitter.com/hashtag/beginner?src=hash&amp;ref_src=twsrc%5Etfw">#beginner</a> <a href="https://t.co/26KaNpEbzk">pic.twitter.com/26KaNpEbzk</a></p>&mdash; Durga Pokharel (@mathdurga) <a href="https://twitter.com/mathdurga/status/1354801914290966534?ref_src=twsrc%5Etfw">January 28, 2021</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>