Generator expressions are similar to List Comprehensions but more memory-efficient:

  • Instead of creating a complete list in memory, it generates values one at a time
  • Uses parentheses () instead of square brackets []

When refactoring the bar tab project with an object-oriented programming approach using classes, I used a generator expression for the get_totals() method:

# calulcate totals
def get_totals(self):
	self.subtotal = sum(price for drink, price in self.drinks)
	self.tip = round(self.subtotal * 0.20, 2)
	self.grand_total = self.subtotal + self.tip
  • price for drink, price in self.drinks generates each price in the list one at a time
  • The sum() function adds up the prices as they’re generated
    • more efficient process than first creating a list of all prices

The benefits of using generator expressions:

  • Uses less memory since it doesn’t store all values at once
  • Great for large datasets or when you only need to iterate once
  • Perfect for functions like sum(), max(), min() that just need to process values