Skip to content

Instantly share code, notes, and snippets.

@mysticBliss
Last active February 2, 2018 06:33
Show Gist options
  • Save mysticBliss/41fb6e2cd7eeacf8d310f7932313c59c to your computer and use it in GitHub Desktop.
Save mysticBliss/41fb6e2cd7eeacf8d310f7932313c59c to your computer and use it in GitHub Desktop.
Generator

Generator(s): python

Yield result one by one!

Generators are used to create iterators, but with a different approach. Generators are simple functions which return an iterable set of items, one at a time, in a special way.

When an iteration over a set of item starts using the for statement, the generator is run. Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the for loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.

Fibonacci series

def fib():
    a=0
    b=1
    while True:
        yield a
        a,b=b,a+b

# print series till 100 numbers

for n in fib():
    if n>100:
        break
    print n
    

# Check if it is a generator?

import types    
type(fib()) == types.GeneratorType

Simple Zip Function

name=['a','b','c']

def marks(mark):
    for m in mark:   
        if m == None:      
            raise StopIteration
        else:
            yield m
            
m_ = marks(mark=[1,2,3])

for n in name:
    print str(n) +' '+ str(next(m_))
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment