1. Home
  2. Docs
  3. Python 201
  4. Generator Expressions

Generator Expressions

In this lesson you learn generator expressions.

GeneratorExpressions

 
List Comprehensions are not memory efficient, as all the

elements are created at once. If you want a list with

large data set, then don’t use list comprehensions.

Alternative to list comprehensions are generator expressions

Generate expression, generate successive values,

values can be accessed using next() built in function.

Syntax:
  

(expr for var in interable [filter condition])
 

  
Note there is not much difference in terms of syntax, only [ ] square brackets are

replaced with ( ) round brackets.

To understand generator expressions, consider our first example

num_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  

Now let’s create this list using generator expression.


num_list = (num for num in range(10))

num_list

output:

<generator object <genexpr> at 0x000001C3D462BA98>

  
And items can be accessed using next() built in method.

next(num_list)

output:

0

next(num_list)

output:

1

  

T-shirts with color and sizes.

  

colors = ['Royal Blue', 'Grey']

sizes = ['S','M','L','XL']

tshirts = ((color, size) for color in colors for size in sizes)

print(tshirts)

output:

<generator object <genexpr> at 0x000001C3D47BEDB0>

# access the element

next(tshirts)

output:

('Royal Blue', 'S')

# access next element

next(tshirts)

output:

('Royal Blue', 'M')