Blog

Filter posts by Category Or Tag of the Blog section!

Understanding the python generators

Monday, 07 December 2015

In simple words, generators are a way of creating iterators. A generator is a function that returns an object that can iterate over in a fast, easy, and clean way. You can use it with a for a statement or use the next function. 


 

1
2
3
4
5
6
7
8
9
10
11
def aGen(n):
 
    yield n
 
    yield n + 1
 
    
 
for n in aGen(4):
 
 print(n)

 

As you can see, in the above code: aGen() is a function that yields n and n+1. Rather than that we can use the expression to create a generator:

 

1
2
3
a = (x * x for x in range(100))
 
print(sum(a))

 

As I mentioned, we can use the next function as well:

 

1
2
3
g = (n for n in range(3, 5))
 
g.next()

Category: Software

Tags: Python