Generators in Python | Python Programming
Generators in Python: Generators are special type of functions in Python. Normal functions in python returns some value at the end of function execution. But generator instead of returning value, it returns an iterable generator object. We can fetch one value at a time from an iterable generator object. We cannot fetch the complete list of values, we need to use for loop to fetch all values.
How to create Generator function
- We can create generator using generator function.
- Use of yield keyword is necessary to define a generator function
- Instead of return we use yield keyword.
- For loop is used to fetch all values using iterable generator object.
Example 1: Let’s create our own generator function.
#Example generator function def generator(): for i in range(1,5): yield i z = generator() print(z)
Output:
#Output <generator object generator at 0x7fc6f69e7d38>
Explanation: Here z is iterable generator object. We need to use for loop along with generator object to get list of value.
Example 2: Let’s implement for loop along with generator object to get the output.
#Example generator function def generator(): for i in range(1,5): yield i z = generator() for i in z: print(i)
Output:
#Output 1 2 3 4
So, this is how Generator in Python works.
Normal Function: Let’s take an example of normal function.
#Example Normal function def normalFunction(): x = 20 y = 24 return x+y z = normalFunction() print(z)
Output:
#Output 44
Output: Normal function returned the 44.
Generator Function: Let’s take an example of generator function.
#Example generator function def generator(): x = 20 y = 24 yield x+y z = generator() print(z)
Output:
#Output <generator object generator at 0x7f9f1a967cf0>
Output: Generator function returned the <generator object generator at 0x7f9f1a967cf0>.
There are three ways to get complete values from Generator Object returned by generator.
1). Using for loop
2). Using list()
3). Using next()
(i). Using for loop():
#Using for loop def generator(): for i in range(1,5): yield i z = generator() for i in z: print(i)
Output:
#Output 1 2 3 4
(ii). Using next():
#Example using next function def generator(): for i in range(1,6): yield i z = generator() print(next(z)) print(next(z)) print(next(z)) print(next(z)) print(next(z))
Output:
#Output 1 2 3 4 5
(ii). Using list():
#Example using list function def generator(): for i in range(1,6): yield i z = generator() print(list(z))
Output:
#Output [1, 2, 3, 4, 5]
Summary or Conclusion:
1). Generators are one time used ie. when generator function is called it return iterable generator object.
2). Generators does not store any value or anything in memory.
3). Three ways to read values from generator object ie. next(), for loop() and list() methods.
So, that’s all about Generators in Python Programming.