Introduction to generators

In the series of intermediate python, now we are going to discuss generators in Python. Please don’t confuse between generator and iterator. Generators are different from the iterator.

In a generator, unlike a normal function, we use yield instead of return. If in a function we are using yield then it is automatically converted to the generator. Generators have function next in order to access next value generated from yield. As generators are not storing values in memory. Generators are also returning an iterator. So, we can iterate over iterators to access values as well.

We will see how to make generators through example.

How to make a Generator function?

In [19]:
## Defining a generator function

def iterating_num(n):
    i =0
    for j in range(n):
        i = i+1
        yield(i)
        
 

Accessing values generated from generator function

In [20]:
## Iterating with values generated from generatoors as an iterator

for e in iterating_num(6):
    print(e)
 
1
2
3
4
5
6

next() method

In [21]:
## Iterating using next function
## first creating object.

my_nums = iterating_num(6)
In [22]:
## Using next function

print(next(my_nums))
print(next(my_nums))
print(next(my_nums))
 
1
2
3
 

Generator Comprehension

In [31]:
## It is similar to list comprehension. Insted of "[]" brackets, use "()" for generator compheresion
iterating_nums = (i+1 for i in range(6))

## It is returning generator object
## In order to access values either use next or "for in"
iterating_nums
Out[31]:
 at 0x0000020AD85FD468>
In [32]:
next(iterating_nums)
Out[32]:
1
In [33]:
## Using "for in" loop we are trying to access values

## Here you can see that we are getting values from 2. Why is it so? Because in previous step we used next() on genetor, 
## hence it is pointing to next point thats why its started from 2 
for e in iterating_nums:
    print(e)
 
2
3
4
5
6

Moreover, generator use “yield” keyword and yield is only storing a current value in memory. Hence, generators are memory efficient as well.

So, this is all for generators. Hope you enjoyed learning generators.

Stay tuned for more amazing blogs on intermediate python.