Generator Expression in Python: What It Is and How It Works
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.
squares = (x * x for x in range(5)) for num in squares: print(num)
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.