Generator Comprehensions

Learn when and how to use generator comprehensions.

What is a generator comprehension?

A generator comprehension is similar to a list comprehension, which we learned about in an earlier chapter. The difference is that a generator comprehension uses lazy evaluation, which often uses less memory and allows infinite iterators to be processed.

Converting a list comprehension to a generator comprehension is a simple matter of replacing the surrounding square brackets with round brackets. For example, the following code from the list comprehension chapter creates a list of strings: ‘0’, ‘1’, ‘2’, etc.

Get hands-on with 1400+ tech skills courses.