Lambda Expression

Python Generators

  • In this article, you’ll learn how to create iterations easily using Python generators, how it is different from iterators and normal functions, and why you should use it.
  • 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.
  • let’s us to create a generator we have to define a function in this time not a class.
  • let’s create a function with name top10 which will return you iterator but hold down a function can’t give you an iterator it’s means a function has to be something special so we have to convert this function into generator.
  • normally a function returns a value by using return keyword
Lambda Expression

def top10():

    return 2

values=top10()

print(values)

output

          2

  • But now I just use yield keyword in place of return keyword which will make your function as generator but now you will think the what’s difference between return 2 or yield 2.
  • return 2 give you value when you call the function
  • yield 2 will not give you value .it will give you an object of generator.

def top10():

    yield 2

values=top10()

print(values)

  output

<generator object top10 at 0x000001FF1D293AC8>

  • 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.
  • Generator gives you an iterator so this function is not a normal function this is a generator because we are using yield  if you using return  then you can expect to behave normally it will return 2 but yield will be different  it will it return in the format of generator and everyone knows if you want to fetch iterator  we have to use the next function

Create Generators in Python

  • we can create a generator in python just by simply defining a normal function, but with a yield statement instead of a return statement.
  • If we define a function in python with return keyword then that function act as a normal function.
  • But when we define a function in python with yield keyword then that function will not act as normal function then it becomes a generator function
  • A normal function can contain at most one return keyword.
  • A generator function can contain at least one yield statement (it may contain other yield or return statements),
  • Both yield and return will return some value from a function. Return keyword return a value from function where yield keyword returns a generator from function.
  • The difference is that while a return statement terminates a function entirely, yield statement pauses the function saving all its states and later continues from there on successive calls.

Example Create Generators in Python with single yield keyword: –

# A simple generator function

def top10():

    # Generator function contains yield statements

    yield 2

# It returns an object but does not start execution immediately.

values=top10()

print(values)

print(values.__next__())

print(“=====================”)

# We can iterate through the items using next().

print(next(values))

 output

<generator object top10 at 0x00000289B55B93C8>

2

Example Create Generators in Python with multiple yield keyword: –

# A simple generator function

def top10():

    # Generator function contains yield statements

    n=1

    yield n

    n+=1

    yield n

    n+=1

    yield n

    n+=1

    yield n

# It returns an object but does not start execution immediately.

values=top10()


# Iterating over the generator object using next

# We can iterate through the items using next().

print(next(values))

print(next(values))

print(next(values))

print(next(values))

One interesting thing to note in the above example is that the value of variable n is remembered between each call.

Unlike normal functions, the local variables are not destroyed when the function yields. Furthermore, the generator object can be iterated only once.

To restart the process we need to create another generator object using something like values=top10()

One final thing to note is that we can use generators with for loops directly.

This is because a for loop takes an iterator and iterates over it using next()

# A simple generator function

def top10():

    # Generator function contains yield statements

    n=1

    yield n

    n+=1

    yield n

    n+=1

    yield n

    n+=1

    yield n

# It returns an object but does not start execution immediately.

values=top10()

# We can iterate through the items using  for loop also.

for item in values:

    print(item)

Python Generators with a Loop

Normally, generator functions are implemented with a loop having a suitable terminating condition.

Let’s take an example of a generator that find the perfect square of top 10 number.

# A simple generator function

def top10():

    # Generator function contains yield statements

    n=1

    while n<=10:

        sq=n*n

        yield sq

        n+=1

# It returns an object but does not start execution immediately.

# values is a generator object

values=top10()

# We can iterate through the items using  for loop also.

for item in values:

    print(item)

As now we seen another example, below is a generator for generating Fibonacci Numbers.

# A simple generator for Fibonacci Numbers

def fib(limit):

     # Initialize first two Fibonacci Numbers 

    a, b = 0, 1

    # One by one yield next Fibonacci Number

    while a < limit:

        yield a

        a, b = b, a + b

# Create a generator object

x = fib(5)

# Iterating over the generator object using next

print(next(x))

print(next(x))

print(next(x))

print(next(x))

print(next(x))

# Iterating over the generator object using __next__

print(x.__next__())

print(x.__next__())

print(x.__next__())

print(x.__next__())

print(x.__next__())

# Iterating over the generator object using for

# in loop

# A simple generator for Fibonacci Numbers

def fib(limit):

    # Initialize first two Fibonacci Numbers 

    a, b = 0, 1

    # One by one yield next Fibonacci Number

    while a < limit:

        yield a

        a, b = b, a + b

# Create a generator object

x = fib(5)

# Iterating over the generator object using next

print(x.next()) # In Python 3, __next__()

print(x.next())

print(x.next())

print(x.next())

print(x.next())

# Iterating over the generator object using for

# in loop.

print(“\nUsing for in loop”)

for i in fib(5): 

    print(i)

Leave a Comment

Your email address will not be published. Required fields are marked *