QA
Beginner LevelPython

What is the difference between a List Comprehension and a Generator Expression in Python?

❓ Interview Prompt: Compare list comprehensions [x for x in items] vs generator expressions (x for x in items) regarding memory consumption and lazy evaluation.

Both expressions allow transforming and filtering sequences concisely without writing verbose 'for' loops:

1. List Comprehension ('[x for x in items]'):

•
Enclosed in square brackets '[]'.
•
Eagerly evaluates the entire loop and allocates a complete new list object in RAM immediately.

2. Generator Expression ('(x for x in items)'):

•
Enclosed in parentheses '()'.
•
Lazy evaluation: Does NOT generate the entire list in RAM! Yields one item at a time on demand.
•
Memory Efficient: Transforming 1,000,000 numbers in a list comprehension consumes ~8MB RAM; a generator expression consumes ~200 bytes!

Code Implementation Example

python
import sys

# 1. List Comprehension: Allocates 1,000,000 integers in RAM immediately
list_comp = [x * 2 for x in range(1_000_000)]
print('List Comp RAM:', sys.getsizeof(list_comp), 'bytes') # ~8.4 MB

# 2. Generator Expression: Lazy evaluation, generates items on the fly!
gen_expr = (x * 2 for x in range(1_000_000))
print('Generator RAM:', sys.getsizeof(gen_expr), 'bytes') # ~200 bytes!
💡Memory comparison between List Comprehension and Generator Expression.
🎯 Interview Key Takeaway

Use generator expressions (x for x in items) when processing large datasets to evaluate items lazily and conserve memory.

#List Comprehension#Generator#Memory#Beginner
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?