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. 


 

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:

 

a = (x * x for x in range(100))

print(sum(a))

 

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

 

g = (n for n in range(3, 5))

g.next()

Category: Software

Tags: Python

comments powered by Disqus