0
0
PythonConceptBeginner · 3 min read

Generator Expression in Python: What It Is and How It Works

A generator expression in Python is a compact way to create a generator without defining a full function. It produces items one by one, saving memory by generating values on the fly instead of storing them all at once.
⚙️

How It Works

Imagine you want to get numbers one at a time instead of all at once, like a vending machine that gives you one snack per request instead of handing you the whole shelf. A generator expression works similarly by producing each value only when you ask for it.

This means it doesn't keep all the results in memory, which is great when working with large data or infinite sequences. It looks like a list comprehension but uses parentheses () instead of square brackets [].

💻

Example

This example creates a generator expression that produces squares of numbers from 0 to 4. It then prints each value one by one.

python
squares = (x * x for x in range(5))
for num in squares:
    print(num)
Output
0 1 4 9 16
🎯

When to Use

Use generator expressions when you want to save memory and only need to process items one at a time, such as reading large files, streaming data, or working with infinite sequences. They are perfect for loops where you don't need to keep all results simultaneously.

For example, if you want to calculate the sum of squares for a huge range without creating a big list, a generator expression is efficient and fast.

Key Points

  • Generator expressions use parentheses () and produce items lazily.
  • They save memory by generating values on demand.
  • They look like list comprehensions but do not create a full list.
  • Useful for large data or infinite sequences.

Key Takeaways

Generator expressions create values one at a time, saving memory.
They use parentheses and look like list comprehensions.
Ideal for processing large or infinite data streams efficiently.
Use them when you don't need all results stored at once.