Python | Generator Expressions (original) (raw)

Last Updated : 4 Dec, 2025

In Python, iterators can be created using both regular functions and generators. Generators are similar to normal functions, but instead of return, they use the yield keyword. This allows the function to pause, save its state, and resume later making generators efficient and memory-friendly.

Generators are especially useful when working with large sequences because they produce values one at a time, only when needed (lazy evaluation), instead of storing the entire sequence in memory.

**Example: This example only shows how to define a generator using yield.

Python `

def simple_gen(): yield "A" yield "B" yield "C"

`

**Explanation:

Two built-in functions, next() and iter(), make generators easy to use and help them work seamlessly with Python’s iterator protocol.

**Example: This generator prints a message before yielding each value, showing how the function pauses and resumes.

Python `

def generator(): t = 1 print('First result is', t) yield t

t += 1
print('Second result is', t)
yield t

t += 1
print('Third result is', t)
yield t

call = generator() next(call) next(call) next(call)

`

Output

First result is 1 Second result is 2 Third result is 3

**Explanation:

Difference between Generator function and Normal function

What Are Generator Expressions

A generator expression is a shorter and more compact way to create a generator without using a function or yield. It looks similar to a list comprehension, but uses parentheses () instead of brackets [].

**Key Characteristics

**Syntax

(expression for element in iterable if condition)

This provides the convenience of comprehensions with the efficiency of generators.

**Example: This generator expression computes squares of numbers from 0 to 9 one-by-one.

Python `

generator = (num ** 2 for num in range(10)) for num in generator: print(num)

`

Output

0 1 4 9 16 25 36 49 64 81

**Explanation:

Creating a List Using a Generator Expression

Even though generator expressions produce values lazily, you can convert them into a list.

Python `

string = 'geek' li = list(string[i] for i in range(len(string)-1, -1, -1)) print(li)

`

Output

['k', 'e', 'e', 'g']

**Explanation: