Generator Expression:
To build iterators in Python, we can use both standard functions and generators. Generators are written in the same way as regular functions, except we use yield() instead of return() to return a value. It is more effective as an iterator implementation tool. It is simpler and more convenient to implement since it provides element evaluation on demand. Unlike normal functions, which stop when they experience a return statement, generators use a yield statement, which saves the state of the function from the previous call and can be picked up or resumed the next time we call a generator function. Another significant benefit of the generator over a list is that it consumes much less memory.
List Comprehension:
When you want to generate a new list based on the values of an existing list, list comprehension provides a shorter syntax.
List Comprehension vs Generator Expression
1)Use of Generator Expression
Often we only want to work on a few elements, and we only want to work on them one at a time. In such cases, we can avoid storing unnecessary elements in memory by using lists, sets, or tuples.
As an example, suppose we want to measure the sum of all the numbers in the range 1 to 10000 that are divisible by 2 and 3.
i)Using List Comprehension
Below is the implementation:
# Create a list of numbers in the range 1 to 10000 that are divisible by 2 and 3. numslist = [n for n in range(10000) if n % 2 == 0 and n % 3 == 0] # Calculate the sum of the list list_sum = 0 for element in numslist: list_sum += element print('Sum of list elements = ', list_sum)
Output:
Sum of list elements = 8331666
We made a list of numbers, numslist, and then iterated over each variable in the list to compute the count. Creating a list of too many elements and keeping them in memory was wasteful in this case, and it could have been prevented by using Generators.
ii)Using Generator Expression to calculate the sum
Since we just needed the sum, there is no need to make a long list of these numbers and then calculate the sum. The most effective method is to create a Generator for these selected numbers and then iterate over them one by one using the generator object to obtain the sum. This way, we won’t have to hold all of the elements that aren’t required in memory.
Below is the implementation:
def checkNumber(): # A generator that produces multiples of 2 and 3 in the range 0 to 10000. for number in range(10000): if number % 2 == 0 and number % 3 == 0: yield number # initializing the numbobj with the value returned by checkNumber numObj = checkNumber() # Calculate the sum of the list list_sum = 0 for element in numObj: list_sum += element print('Sum using generator expression = ', list_sum)
Output:
Sum using generator expression = 8331666
2)Generator Expression
A generator expression is used in Python to create Generators. In syntax, it appears to be List comprehension, however ( ) are used instead of [].
Let’s use Generator Expression to find the sum of numbers divisible by 2 and 3 in the range 1 to 10000.
Make a Generator expression that yields a Generator entity.
Below is the implementation:
# initializing the numbobj using generator expression numObj = (n for n in range(10000) if n % 2 == 0 and n % 3 == 0) # Calculate the sum of the list list_sum = 0 for element in numObj: list_sum += element print('Sum using generator expression = ', list_sum)
Output:
Sum using generator expression = 8331666
3)Generator Expression vs List Comprehension
Except for the brackets, the syntax of a Generator expression is identical to that of a List Comprehension, but the key distinction between the two is that the latter returns a Generator object rather than a list. We should use Generators when we just want to loop over the items one at a time and avoid having redundant elements in memory, as shown in the preceding examples.
Related Programs:
- python open a file using open with statement and benefits explained with examples
- python break keyword explained with examples
- python for loop explained with examples
- python iterator iterable and iteration explained with examples
- python how to create a list and initialize with same values
- python sort a list of numbers in ascending or descending order list sort vs sorted
- numpy where explained with examples