PYTHON LIST COMPREHENSION

Build, filter, and transform lists concisely and efficiently in a single readable line of code in Python.

⚡ What is List Comprehension in Python?

List comprehension provides a compact and elegant way to create new lists based on existing iterables (like lists, ranges, or strings). Instead of writing multi-line for loops with .append() methods, list comprehensions combine the loop and conditional filtering into a single expressive statement, improving both code readability and execution speed.

1. Basic Syntax & Comparison with Traditional Loops
Compare a standard multi-line for loop with a clean, one-line list comprehension statement.
Python
# Traditional For Loop Approach
squares_loop = []
for x in range(1, 6):
    squares_loop.append(x ** 2)

# List Comprehension Approach [expression for item in iterable]
squares_comp = [x ** 2 for x in range(1, 6)]

print("Traditional Loop Result:", squares_loop)
print("List Comprehension Result:", squares_comp)
Output: Traditional Loop Result: [1, 4, 9, 16, 25] List Comprehension Result: [1, 4, 9, 16, 25]
Real-Time Example 1: Filtering Active User Accounts
Filter a dictionary or list of user objects to extract only active accounts using conditional list comprehension.
Python
users = [
    {"name": "Rahul", "active": True},
    {"name": "Priya", "active": False},
    {"name": "Amit", "active": True},
    {"name": "Sneha", "active": False}
]

# Extract names of only active users
active_usernames = [user["name"] for user in users if user["active"]]

print("Active Users:", active_usernames)
Output: Active Users: ['Rahul', 'Amit']
Real-Time Example 2: E-Commerce Currency Conversion (INR to USD)
Transform product prices stored in Indian Rupees (INR) into US Dollars (USD) across an entire cart list.
Python
prices_inr = [450, 1200, 3500, 850]
exchange_rate = 83  # 1 USD = 83 INR

prices_usd = [round(price / exchange_rate, 2) for price in prices_inr]

print("Prices in INR:", prices_inr)
print("Prices in USD:", prices_usd)
Output: Prices in INR: [450, 1200, 3500, 850] Prices in USD: [5.42, 14.46, 42.17, 10.24]
Real-Time Example 3: String Cleaning & Formatting
Strip trailing whitespace and capitalize messy user-submitted tags using string methods in comprehension.
Python
raw_tags = ["  python ", "javascript ", "  html", "css  "]

# Clean whitespace and convert to uppercase
cleaned_tags = [tag.strip().upper() for tag in raw_tags]

print("Cleaned Tags:", cleaned_tags)
Output: Cleaned Tags: ['PYTHON', 'JAVASCRIPT', 'HTML', 'CSS']
Real-Time Example 4: Extracting File Extensions (Log Processing)
Isolate and filter specific file types (like .pdf reports) from a mixed server directory list.
Python
server_files = ["report_q1.pdf", "image_logo.png", "invoice_001.pdf", "notes.txt"]

pdf_reports = [file for file in server_files if file.endswith(".pdf")]

print("Identified PDF Reports:", pdf_reports)
Output: Identified PDF Reports: ['report_q1.pdf', 'invoice_001.pdf']
Real-Time Example 5: Using If-Else Conditional Expressions
Apply inline if-else logic inside comprehension to categorize items (e.g., grading marks as Pass or Fail).
Python
student_marks = [85, 42, 90, 38, 72]

# Categorize each mark: "Pass" if >= 50 else "Fail"
results = ["Pass" if mark >= 50 else "Fail" for mark in student_marks]

print("Marks:", student_marks)
print("Results:", results)
Output: Marks: [85, 42, 90, 38, 72] Results: ['Pass', 'Fail', 'Pass', 'Fail', 'Pass']
Real-Time Example 6: Flattening a 2D Matrix Grid
Flatten a multi-dimensional 2D list matrix into a single 1D list using nested list comprehension.
Python
matrix_2d = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Flattening 2D matrix into 1D list
flattened_1d = [num for row in matrix_2d for num in row]

print("Original 2D Matrix:", matrix_2d)
print("Flattened 1D List:", flattened_1d)
Output: Original 2D Matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Flattened 1D List: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Real-Time Example 7: Generating Combinatorial Product SKUs
Create variant SKU codes combining sizes and colors in a single line.
Python
sizes = ["S", "M", "L"]
colors = ["Red", "Blue"]

skus = [f"Tee-{size}-{color}" for size in sizes for color in colors]

print("Generated Product SKUs:", skus)
Output: Generated Product SKUs: ['Tee-S-Red', 'Tee-S-Blue', 'Tee-M-Red', 'Tee-M-Blue', 'Tee-L-Red', 'Tee-L-Blue']
Real-Time Example 8: Removing Vowels from User Input (Text Processing)
Filter out vowels from a string using comprehension to generate a consonant-only text abbreviation.
Python
sentence = "Python Programming"
vowels = "aeiouAEIOU"

consonants_only = "".join([char for char in sentence if char not in vowels])

print("Original Sentence:", sentence)
print("Without Vowels:", consonants_only)
Output: Original Sentence: Python Programming Without Vowels: Pythn Prgrmmng
Real-Time Example 9: Generating Prime Numbers
Find all prime numbers up to 50 using advanced filtering list comprehension.
Python
primes = [n for n in range(2, 50) if all(n % i != 0 for i in range(2, int(n ** 0.5) + 1))]

print("Prime Numbers up to 50:", primes)
Output: Prime Numbers up to 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]