![]() |
Normal functions in Python are used for traditional computation tasks, with execution proceeding from start to finish, typically returning a single result. On the other hand, generator functions employ the `yield` statement to produce values lazily, preserving their state across multiple calls. This allows generators to efficiently handle large datasets or infinite sequences by yielding values one at a time and pausing execution when necessary, making them a valuable tool for memory-efficient and iterative tasks. In this article, we’ll look into Python generator functions and normal function differences i.e. how different are their syntax, how is data handled, and practical applications. What are Python Generators?Generator functions in Python make it easy to generate data, allowing for efficient memory utilization and lazy evaluation. That is totally different from normal functions, which run completely and return a single value, but generator functions simply employ the ‘yield’ keyword to generate values one at a time as the condition is stated. Because of this difference, generator functions are suited for working with enormous datasets or infinite sequences. Yield statementYield statement allows a generator function to produce a value to the caller without losing the current state of the function. When the generator function is called again, execution resumes from where it left off, continuing to yield values one at a time. Let us see its syntax def generator_function(): Now we will see an example of a generator function to understand it better: Python3
Output
2 4 Normal function in PythonNormal function performs a specific task and can be called from other parts of the program. Also normal function return a single value and terminate the session. Python3
Output
2 4 As you can see, the generator function uses the yield keyword instead of return and generates values as they are needed, rather than creating a list of all values at once. Difference between generator and normal functionThe generator function in Python is normally defined like a normal function, using the @’ keyword. If we need to generate value Generator functions make use of the yield keyword rather than using return. The major difference between the generator and normal function may be that the Generator function runs when the next() function is called and not by its name as in the case of normal functions.
|
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |