Understanding the basics of generators and implementing them in Python
Python Generator functions allow you to declare a function that behaves likes an iterator, allowing programmers to make an iterator in a fast, easy, and clean way. An iterator is an object that can be iterated or looped upon. It is used to abstract a container of data to make it behave like an iterable object. Examples of iterable objects that are used more commonly include lists, dictionaries, and strings.
In this article, we will learn to create and use generators in Python with the help of some examples.
Let’s first look at a simple class-based iterator to produce odd numbers:
class get_odds:
def __init__(self, max):
self.n=3
self.max=max
def __iter__(self):
return self
def __next__(self):
if self.n <= self.max:
result = self.n
self.n += 2
return result
else:
raise StopIteration
numbers = get_odds(10)
print(next(numbers))
print(next(numbers))
print(next(numbers))
## Output
3
5
7
As you can see a sequence of odd numbers are generated. To generate this, we created a custom iterator inside the get_odds class. For an object to be an iterator it should implement the iter method which will return the iterator object, the next method will then return the next value in the sequence and possibly might raise the StopIteration exception when there are no values to be returned. As you can see, the process of creating iterators is lengthy, which is why we turn to generators. Again, python generators are a simple way of implementing iterators.
python python-generators data-science programming machine-learning
🔵 Intellipaat Data Science with Python course: https://intellipaat.com/python-for-data-science-training/In this Data Science With Python Training video, you...
Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.
Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.
Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.
Practice your skills in Data Science with Python, by learning and then trying all these hands-on, interactive projects, that I have posted for you.