Want to know about Python generators? Read this article to know more about what are Python generators, Python iterator, and also Python Generator vs Iterator.
New to Python? check out Python programming for the absolute beginner.
We will coder:
- What are Python generators
- What are Python Iterators
- Python Generator vs Iterator
- Python generator function
- Python generator next
- Python generator expression
- Python convert generator to an iterator
- Python generator vs iterator performance
Python generator
A Python generator is a function that creates a sequence of values by using the yield method. Here the yield keyword is used rather than return.
Here, we can see how to generate the numbers in python
In this example, to generate numbers from the given range, I have defined a function n(), the yield is used to generate the numbers. When we use the yield keyword the function becomes a generator in Python.
Example:
def n(number):
for i in range(number):
yield i
for number in n(5):
print(number)
Below screenshot shows the output:
In this output, we can see the numbers get iterated the total number of numbers depends on the range that we have mentioned in the range().
Generator for a string in Python
In this example, we can see how to iterate a given string using the yield keyword in python. Here I have defined a function string and assigned the range of the string as length, and then called yield to iterate the string print(string) to get the final value.
Example:
def string(my_string):
length = len(my_string)
for i in range(length):
yield my_string[i]
for string in ("python"):
print(string)
Below screenshot shows the output:
In this output we can see the string python is iterated.
Python generator function
Now, we can see how to print number using generator function in python
In this example, to generate numbers from the given range, I have defined a function n(), the yield keyword is used to generate the numbers. When we use the yield keyword the function becomes a generator.
.
Example:
def n(number):
for i in range(number):
yield i
for number in n(5):
print(number)
Below image shows the output:
In this output, we can see the numbers get iterated the total number of numbers depends on the range that we have mentioned in the range().
Python generator next
Now, we can see python generator using next() in python
In this example, I have defined a function as numberGenerator and assigned number = 2, while loop is used . counter ia subclass which is used to count the hashable objects.
Example:
def numberGenerator(n):
number = 2
while number < n:
yield number
number += 2
g = numberGenerator(20)
counter = 0
while counter < 9:
print(next(g))
counter += 1
Below screenshot shows the output:
In this output we can see the sequence of fibonacci numbers.
Python generator expression
Here we can see about python generator expression in python.
The generator expressions are similar to list compression, generator expressions create a list without yield keyword. In this example, I have taken a variable as a number and performed an addition operation for the number using range(). lastly, to print each number which is in the range I have used a print statement.
Example:
number = (x+x+x for x in range(10))
for each in number:
print(each)
Below screenshot shows the output:
In this output, we can see that the output number we are getting is added three times, The arithmetic operation performed here is considered as the expression.
Python generator class
In this we can see how to write generator class in python
In the below example, I have taken init() to initialize the objects and self indicates the instance of the class, self keyword is used to access the attributes and methods from the class self.num1, self.num2 = 1, 2 are the attributes of the class.
def __next__(self) is used to iterate the next object, the yield is used for calling a block and the range() function returns a list of from the given range.
Example:
class fibonacci:
def __init__(self, num):
self.num = num
self.num1, self.num2 = 2, 3
def __iter__(self):
for i in range(self.num):
yield self.num1
self.num1, self.num2 = self.num2, self.num1+self.num2
f = fibonacci(3)
for i in f:
print(i)
Below screenshot shows the output:
In this output, we can see the 3 fibonacci numbers
Python generator connecting
Now we can see how generator connect themselves in python.
In the below example, I have taken 3 generators as myGeneratora,myGeneratorb,myGeneratorc, The first generator is myGeneratora has an input parameter which gives the limit in the range, the second generator is myGeneratorb has two parameters as input which gives two limits in the range, next mygeneratorc calls myGeneratora and myGeneratorb to yield their values and print is used to print the values.
Example:
def myGeneratora(n):
for i in range(n):
yield i
def myGeneratorb(n, m):
for j in range(n, m):
yield j
def myGeneratorc(n, m):
yield from myGeneratora(n)
yield from myGeneratorb(n, m)
yield from myGeneratorc(m, m+10)
print(list(myGeneratora(0)))
print(list(myGeneratorb(1, 5)))
print(list(myGeneratorb(0, 10)))
Below screenshot shows the output:
In this output, we can see how the generators are connecting.
Python generator vs iterator
Before understanding the difference between Python generator vs iterator, let us first understand what is a Python iterator.
Python Iterator
The Python Iterator is a object that return one element at a time, and the next() is used for getting the next value.
Here, we can see how to iterate the items from the list in python.
In this example, I have assigned a list name as my_list, iter() returns an iterator for the object .next() returns the next item from an iterator.
Example
my_list = [1, 2, 3, 4, 5]
my_iter = iter(my_list)
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
Below Screenshot shows the output:
In this output, we can see the items iterated from the list and the number of items that is iterated depends on number of print(next(my_iter))statement.
Iterator using class
Now, we can see how to iterate the numbers using class in python.
In this example, I have defined a class EvenNumber, It creates an iter and then returns numbers in the order(2,4,6,8,10,12), The six numbers are iterated because I have used 6 print(next(myiter)) statements. self is a parameter that is used to access the variables that belong to that class.
Example:
class EvenNumbers:
def __iter__(self):
self.a = 2
return self
def __next__(self):
numbers = self.a
self.a += 2
return numbers
myclass = EvenNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
In this output we can see the numbers return in the order, six numbers are returned as I have used six print(next(myiter)) statements.
Python Generator vs Iterator
Generator | Iterator |
The yield keyword is used to iterate a value. | The return keyword is used to iterate a value |
Class is not required. | Class is required |
The generator is always an iterator. | The iterator is not always generator. |
All the local variables are stored before in it. | There is no local variable |
To summarize,
- Python generator usually implemented using function and iterator is implemented using class, generators use keyword yield and iterator uses keyword return.
- All the local variables are stored before the yield statement in the generator, there is no local variable in the iterator. In a python generator, we can write fast and neat code.
- To create a generator in python we use the function but to create an iterator function we have to use iterator() and next function().
Python generator vs iterator performance
- Python Generators has more memory and it is much efficient for CPU.
- Python Generators is having good programming construct.
- Iterators allow lazy evaluation.
- Iterators only iterate the next element only when requested.
- Generator and iterators can only be iterated only once.
- Generator functions and generator expressions in Python are better than iterators for simple cases.
Python convert a generator to an iterator
Here, we can see how to convert generator to an iterator in python.
In this example, the yield is used to convert a function into a generator and it returns a generator. When the yield is called it will return the generator.
Example:
def common_divisors_generator(a):
factors_a = [i for i in range(2, a + 2) if a%i == 0]
def gen():
for fa in factors_a:
yield fa
return gen()
print(common_divisors_generator)
Below screenshot shows the output:
You may like the following Python tutorials:
- Python write String to a file
- Command errored out with exit status 1 python
- Python write list to file with examples
- Python generate random number and string
- Python format number with commas
- Python Tkinter Button – How to use
- Python Tkinter radiobutton – How to use
- Python Tkinter Menu bar – How to Use
- Python Counter – Detailed Tutorial
- Python Recursion (Everything you should know)
- Python Comparison Operators
- Python Threading and Multithreading
- How to convert Python degrees to radians
This is how we can work with Python generators and iterators. Here we learned the below things:
- Python generator
- Generator for a string in Python
- Python generator function
- Python generator next
- Python generator expression
- Python generator class
- Python generator connecting
- Python generator vs iterator
- Python Iterator
- Iterator using class
- Python generator vs iterator performance
- Python convert generator to an iterator
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.