Some text some message..
Back 7.2 🧠 Python List Comprehension 21 Jun, 2025

🧠 Python List Comprehension – Detailed Explanation with Examples


🔹 What is List Comprehension?

List comprehension is a concise and elegant way to create lists in Python.

✅ It’s shorter, faster, and more readable than using a traditional for loop.


🔹 Basic Syntax

[expression for item in iterable if condition]

Parts:

  • expression: What to do with each item (e.g., x*x)

  • item: The variable representing each element in the iterable

  • iterable: A sequence (like list, range, string, etc.)

  • condition (optional): A filter for including items


🔹 Example 1: Create a List of Squares

squares = [x**2 for x in range(5)]
print(squares)  # Output: [0, 1, 4, 9, 16]

🔹 Example 2: Filter Even Numbers

evens = [x for x in range(10) if x % 2 == 0]
print(evens)  # Output: [0, 2, 4, 6, 8]

🔹 Example 3: Convert String to List of Characters

chars = [char for char in "Python"]
print(chars)  # Output: ['P', 'y', 't', 'h', 'o', 'n']

🔹 Example 4: Apply Function to List Elements

names = ["Abhi", "John", "Sara"]
lowercase_names = [name.lower() for name in names]
print(lowercase_names)  # ['abhi', 'john', 'sara']

🔹 Example 5: Nested Loops in List Comprehension

pairs = [(x, y) for x in [1, 2] for y in [3, 4]]
print(pairs)  # Output: [(1, 3), (1, 4), (2, 3), (2, 4)]

🔹 With if-else in Expression

labels = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
print(labels)  # Output: ['Even', 'Odd', 'Even', 'Odd', 'Even']

🔹 Real-Life Analogy

Imagine you’re at a fruit shop and want only apples in your basket, but want them in uppercase.

fruits = ["apple", "banana", "apple", "orange"]
only_apples = [fruit.upper() for fruit in fruits if fruit == "apple"]
# Output: ['APPLE', 'APPLE']

🔹 Why Use List Comprehension?

Traditional Loop List Comprehension
More lines of code One-liner and elegant
Less readable when complex More readable and Pythonic
Slightly slower for small operations Faster and optimized in most cases

✅ Summary

  • Fast way to generate or transform lists

  • Use with for, if, and even if-else

  • Avoid overcomplicating – use for clarity, not complexity