DEV Community

loading...

Day 35 Of 100DayOfCode: More About Python Iterator And Generator

iamdurga profile image Durga Pokharel ・3 min read

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)))
Enter fullscreen mode Exit fullscreen mode

When above code run we can get following output,

[[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Discussion (7)

pic
Editor guide
Collapse
roulioo profile image
Pereira Júlio

In the weekend do you also coding ?

Collapse
hentaichan profile image
ヘンタイちゃん

Not the one you're asking, but I am also doing the #100DaysOfCode challenge (I update my progress on twitter though), but yeah I also code on the weekend. You don't have to spend a ton of hours every day, just a little is enough to keep the cycle alive. But you can also play according to your own rules and make a break on weekends.

Collapse
roulioo profile image
Pereira Júlio

Thank you, I'm a Junior Frontend Developer and all ideas of people will help me to create my own routine. Thank you !

Collapse
iamdurga profile image
Durga Pokharel Author • Edited

Yes, I am doing. I am new in this field , I need to learn more, I want to begin my profession in this field so I did not take break even in weekend.

Collapse
iamdurga profile image
Durga Pokharel Author • Edited

Yes I am doing. I am new in this field , I want to begin my profession in this field so did not take break even in weekend.

Collapse
tetrisgameaz profile image
tetrisgameaz

​Really I appreciate the effort you made to share the knowledge. The topic here I found was really effective to the topic which I was researching for a long time.
t rex game

Collapse
iamdurga profile image
Durga Pokharel Author

It's my pleasure.