Generator Expressions
Iterating with generator expressions.
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:
Press + to interact
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 ...
Access this course and 1400+ top-rated courses and projects.