Thursday, 23 September 2021

Python: Generator expressions

Generator expressions are used to define generators effectively. Generator expressions are similar to list comprehensions, but enclosed in () and lazily evaluated.

 

Examples

square_list = (x**2 for x in my_list)

inc_by_10_generator = (inc_by_10(x) for x in my_list)

 

Example 1: Square every element in the list

 

square_every_element_using_generator.py

my_list = [2, 3, 4, 7]

square_list = (x**2 for x in my_list)

print(next(square_list))
print(next(square_list))

 

Output

4
9

 

Example 2: Add 10 to every element in the list.

 

add_10_to_list_using_generator.py

my_list = [2, 3, 4, 7]

def inc_by_10(x):
    return x + 10

inc_by_10_generator = (inc_by_10(x) for x in my_list)

print(next(inc_by_10_generator))
print(next(inc_by_10_generator))

 

Output

12
13

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment