>>> even_squares = (x * x for x in range(10)
if x % 2 == 0)
# Initialize the list
my_list = [1, 3, 6, 10]
# square each term using list comprehension
list_ = [x**2 for x in my_list]
# same thing can be done using a generator expression
# generator expressions are surrounded by parenthesis ()
generator = (x**2 for x in my_list)
print(list_)
print(generator)
>>> listcomp = ['Hello' for i in range(3)]
>>> genexpr = ('Hello' for i in range(3))
>>> genexpr = ('Hello' for i in range(3))
>>> list(genexpr)
['Hello', 'Hello', 'Hello']
>>> iterator = ('Hello' for i in range(3))
>>> for x in iterator:
... print(x)
'Hello'
'Hello'
'Hello'
def generator():
for item in collection:
yield expression
>>> for x in even_squares:
... print(x)
0
4
16
36
64
#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