5.13 Generator Expressions

  • Like list comprehensions, but create iterable generator objects that produce values on demand.
  • Known as lazy evaluation.
  • For large numbers of items, creating lists can take substantial memory and time.
  • Generator expressions can reduce memory consumption and improve performance if the whole list is not needed at once.
In [1]:
numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
In [2]:
for value in (x ** 2 for x in numbers if x % 2 != 0):
    print(value, end='  ')
9  49  1  81  25  
In [3]:
squares_of_odds = (x ** 2 for x in numbers if x % 2 != 0)
In [4]:
squares_of_odds 
Out[4]:
<generator object <genexpr> at 0x110430408>
  • Output indicates that square_of_odds is a generator object that was created from a generator expression (<genexpr>).
  • Built-in function next receives a generator or iterator and returns the next item.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.