Generator Expressions
Iterating with generator expressions.
We'll cover the following...
We'll cover the following...
Generators can be easily created on the fly by using generator expressions.
Generator expression versus list comprehension
The syntax of a generator expression is similar to that of a list comprehension with just one difference: the square brackets are replaced by round parentheses. For example:
Python 3.10.4
orig = [1, 2, 3]listcomp = [n+1 for n in orig] # Designing list comprehennsion out of listgenerator = (n+1 for n in orig) # Designing generator exp. out of listprint(listcomp)print(generator)
We can see that a generator expression doesn’t produce the output directly. It returns a generator object which will produce the items when explicitly told. Whereas, on printing listcomp
, we immediately ...