Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

generator expression python

#Generator expressions

#List comprehension is greedy evaluation, create lists immediately when execute it
#Generator expressions is lazy evaluation, creates an iterable generator object on demand
#Generator uses () instead of []
#Syntax order changes slightly compared to list comprehension

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
for val in (x**2 for x in numbers if x%2 != 0):     # note the () instead of []
    print(val, end = " ")
#1 9 25 49 
 
PREVIOUS NEXT
Tagged: #generator #expression #python
ADD COMMENT
Topic
Name
1+9 =