In Python, Generators are lazy iterators created by generator functions or generator expressions. In this article, I will introduce you to generators in Python. At the end of this article, you will learn what generators are and how to implement them using Python.
What are Generators in Python?
The Generator expressions are similar to a list, dictionary, and set understandings, but are enclosed in parentheses. Parentheses do not need to be present when used as the sole argument for a function call.
Also, Read – When do we need Machine Learning.
expression = (x**2 for x in range(10))
The example above generates the first 10 perfect squares, including 0 (where x = 0).
Generator functions are similar to regular functions, except that they have one or more yield statements in their bodies. These functions cannot return any value.
def function():
for x in range(10):
yield x**2
Code language: JavaScript (javascript)
The generator function above is equivalent to the previous generator expression, it produces the same thing.
All generator expressions have their equivalent functions, but not the other way around. The Generators can also be used without parentheses if both parentheses would be repeated otherwise:
sum(i for i in range(10) if i % 2 == 0) #Output: 20
any(x = 0 for x in foo) #Output: True or False depending on foo
type(a > b for a in foo if a % 2 == 1) #Output: <class 'generator'>
Code language: HTML, XML (xml)
Instead of:
sum((i for i in range(10) if i % 2 == 0))
any((x = 0 for x in foo))
type((a > b for a in foo if a % 2 == 1))
Code language: HTML, XML (xml)
But not:
fooFunction(i for i in range(10) if i % 2 == 0,foo,bar)
return x = 0 for x in foo
barFunction(baz, a > b for a in foo if a % 2 == 1)
Code language: HTML, XML (xml)
The generators functions produce a generator object, which can then be iterated. Unlike other types of iterators, generator objects can only be browsed once.
g1 = function()
print(g1) # Out: <generator object function at 0x1012e1888>
Code language: PHP (php)
Note that the body of generators is not executed in a matter of seconds: when you will call the function() in the example above, it will immediately return a generator object, without executing the print function. This allows generators to consume less memory than functions that return a list, and it allows you to create generators that produce infinitely long sequences.
For this reason, generators are often used in machine learning and other contexts involving large amounts of data. Another advantage of using the generator functions is that it can immediately use the values ​​provided by a function without waiting for the complete sequence to be produced.
I hope you liked this article on the generators in Python. Feel free to ask your valuable questions in the comments section below.
Also, Read – Predict Car Prices with Machine Learning.