Blog

Blog

What are Generators in Python and How to use them?

Youtube banner Logo

Generators in Python

Generators are a type of iterable, like lists or tuples. However, unlike lists, generators do not store all of the values in memory at once. Instead, they generate the values on the fly, which can be very useful for working with large data sets or infinite sequences.

Here’s an example of a simple generator function that generates the squares of numbers, starting from 0:

def squares(n):
    for i in range(n):
        yield i**2for square in squares(5):
    print(square)

Output:

0
1
4
9
16

In this example, the yield keyword is used to indicate that this is a generator function. When the function is called, it returns a generator object, which can be used in a for loop to iterate over the generated values.

Another example is the Fibonacci series generator:

def fibonacci(n):
    a, b = 0, 1for i in range(n):
        yield a
        a, b = b, a + b
for num in fibonacci(10):
    print(num

Output:

0
1
1
2
3
5
8
13
21
34

You can also use the generator inside the list comprehension:

squared_fibonacci = [x**2 for x in fibonacci(10)]
print(squared_fibonacci)

Output:

[0, 1, 1, 4, 9, 25, 64, 169, 361, 841]

You can also use the generator inside the map function :

squared_fibonacci = map(lambda x:x**2,fibonacci(10))
print(list(squared_fibonacci))

Output:

[0, 1, 1, 4, 9, 25, 64, 169, 361, 841]

Another advantage of using generators is that they can be used to represent an infinite sequence, such as the infinite sequence of prime numbers.

Here is an example of a generator function that generates an infinite sequence of prime numbers:

def primes():
    current = 2while True:
        is_prime = Truefor i in range(2, current):
            if current % i == 0:
                is_prime = Falsebreakif is_prime:
            yield current
        current += 1for prime in primes():
    if prime > 20:
        breakprint(prime)

Output:

2
3
5
7
11
13
17
19

Note that the primes() generator function uses the while True loop to generate an infinite sequence of prime numbers. It then uses the yield keyword to return the next prime number in the sequence.

However, it’s important to be careful when working with infinite sequences like this one. In the above example, the primes() generator function is wrapped with a for loop that breaks once the prime number exceeds 20. This is to prevent an infinite loop if the generator function is not used properly.

Another way to use generator function is by using the generator expression.

Here is an example:

squared_fibonacci = (x**2 for x in fibonacci(10))
print(list(squared_fibonacci))

Output:

[0, 1, 1, 4, 9, 25, 64, 169, 361, 841]

The generator expression is similar to list comprehension, but it returns a generator object instead of a list. This can be useful when working with large data sets, as it allows you to work with the data one element at a time, rather than loading the entire data set into memory at once.

Conclusion:

Generators are an important concept in Python that can be used to create iterable objects that generate values on the fly. They can be useful for working with large data sets or infinite sequences, and can also be used in conjunction with other language features such as list comprehensions, the map() function, and generator expressions. Generators are memory efficient and can be used to represent an infinite sequence. However, it’s important to be careful when working with infinite sequences, as they can lead to infinite loops if not used properly. By understanding and utilizing generators in Python, you can write more efficient and effective code.

FAQ’s

Q1 What is a generator in Python?

A generator is a special type of iterator in Python, which is used to create iterators. It is defined using the yield keyword, instead of the return keyword.

Q2 How do you create a generator in Python?

A generator can be created by defining a function using the yield keyword, instead of the return keyword. When the function is called, it returns an iterator object, which can be used to iterate through the items generated by the generator.

Q3 How do you use a generator in Python?

A generator can be used like an iterator, by calling the next() function on it. The generator will return the next item in the sequence, until it reaches a StopIteration exception, indicating that there are no more items to return. You can also use for loop to iterate through generator.

Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
Click outside to hide the comparison bar
Compare

Subscribe to Newsletter

Stay ahead of the rapidly evolving world of technology with our news letters. Subscribe now!