List Comprehension in Python: A Beginner’s Guide with Examples

Madhura AnandMadhura Anand
3 min read

🧠 What is List Comprehension?

List comprehension is a concise and elegant way to create lists in Python. Instead of using multiple lines with for loops and append(), you can generate a new list in just one line.

# Traditional way
squares = []
for x in range(5):
    squares.append(x**2)

# List comprehension
squares = [x**2 for x in range(5)]

💡 Why Was List Comprehension Introduced?

Python emphasizes readability and efficiency. List comprehension was introduced to:

  • Reduce boilerplate code

  • Make your code more readable and Pythonic

  • Enable faster execution (under the hood, comprehensions are optimized)


🧪 Basic Syntax

[expression for item in iterable if condition]
  • expression → what you want to store in the list

  • item → the variable that takes each value in the iterable

  • iterable → any sequence (list, tuple, range, etc.)

  • condition (optional) → filters which items to include


🔁 Examples Using Different Iterables

1. range(): Squares of Numbers

squares = [x*x for x in range(6)]
# [0, 1, 4, 9, 16, 25]

2. list: Filtering Even Numbers

nums = [1, 2, 3, 4, 5, 6]
evens = [x for x in nums if x % 2 == 0]
# [2, 4, 6]

3. string: Extract Vowels

text = "hello world"
vowels = [ch for ch in text if ch in 'aeiou']
# ['e', 'o', 'o']

4. dictionary: Get Keys with Even Values

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
even_keys = [k for k, v in d.items() if v % 2 == 0]
# ['b', 'd']

5. set: Unique Squares

nums = {1, 2, 2, 3}
squares = {x**2 for x in nums}
# {1, 4, 9}

6. Nested Loops (Cartesian Product)

pairs = [(x, y) for x in [1, 2] for y in ['a', 'b']]
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

⚠️ When Not to Use It

Avoid list comprehensions when:

  • The logic becomes too complex (nested conditions + loops)

  • You're modifying multiple data structures (e.g., lists + dicts)

  • You want to add debug statements

Use regular loops for clarity in these cases.


⚙️ How List Comprehension Works Under the Hood

When you write a list comprehension like:

squares = [x * x for x in range(5)]

You might think it’s just a shortcut for:

squares = []
for x in range(5):
    squares.append(x * x)

But behind the scenes, Python doesn't actually call .append() at all.


🔍 What Really Happens

Python turns the list comprehension into a hidden function (called <listcomp>) and passes an iterator into it.

It uses low-level C code to:

  • Pre-allocate memory for the list

  • Compute values like x * x

  • Write them directly into the list — no .append() needed


💡 Why This is Faster

With List ComprehensionWith for Loop + .append()
Memory allocated ahead of timeList grows dynamically
No function call for .append()Calls .append() on each loop
Optimized as a functionSlower due to method calls

If you're curious, using Python's dis module shows that:

  • List comprehensions compile into shorter, optimized bytecode and avoids .append()

  • Loops with .append() require extra steps like LOAD_METHOD append and CALL_METHOD

  • For loop calls .append() every time adding overhead

Once you get the hang of list comprehensions, you'll start seeing them everywhere in Python codebases. Use them for simple transformations and filtering just don’t overdo it when logic becomes complicated.

0
Subscribe to my newsletter

Read articles from Madhura Anand directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Madhura Anand
Madhura Anand