PYTHON LIST COMPREHENSION

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

⚡ What is List Comprehension in Python?

List comprehension provides a compact way to create lists based on existing iterables. Using the syntax [expression for item in iterable if condition], it replaces bulky multi-line for loops and append() statements with clean, highly readable, and optimized bytecode.

1. Basic List Comprehension Syntax
Generate a list of squared numbers from 1 to 5 instantly without traditional loop blocks.
Python
# Generating squares using list comprehension
squares = [x**2 for x in range(1, 6)]

print("Original Range Numbers: [1, 2, 3, 4, 5]")
print("Generated Squares List:", squares)
Output: Original Range Numbers: [1, 2, 3, 4, 5] Generated Squares List: [1, 4, 9, 16, 25]
Real-Time Example 1: Filtering Active User Sessions
Filter an active session user list conditionally to retrieve usernames matching specific criteria.
Python
users = ["nikita_dev", "admin_root", "guest_01", "rahul_lead", "test_user"]

# Filter usernames containing 'dev' or 'lead'
active_developers = [user for user in users if "dev" in user or "lead" in user]

print("All Registered Users:", users)
print("Filtered Developers/Leads:", active_developers)
Output: All Registered Users: ['nikita_dev', 'admin_root', 'guest_01', 'rahul_lead', 'test_user'] Filtered Developers/Leads: ['nikita_dev', 'rahul_lead']
Real-Time Example 2: Cleaning and Formatting Text Fields
Strip trailing whitespace and convert raw user tag inputs to uppercase automatically.
Python
raw_tags = ["  python ", "database ", "  java", "html  "]

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

print("Raw Tags Input:", raw_tags)
print("Formatted Clean Tags:", cleaned_tags)
Output: Raw Tags Input: [' python ', 'database ', ' java', 'html '] Formatted Clean Tags: ['PYTHON', 'DATABASE', 'JAVA', 'HTML']
Real-Time Example 3: Extracting File Extensions from Directory
Parse file lists to isolate specific file formats like PDF or JPEG documents.
Python
directory_files = ["report.pdf", "banner.png", "invoice.pdf", "logo.jpg", "script.py"]

# Extract only PDF filenames
pdf_files = [file for file in directory_files if file.endswith(".pdf")]

print("All Files:", directory_files)
print("Filtered PDF Documents:", pdf_files)
Output: All Files: ['report.pdf', 'banner.png', 'invoice.pdf', 'logo.jpg', 'script.py'] Filtered PDF Documents: ['report.pdf', 'invoice.pdf']
Real-Time Example 4: Parsing and Filtering Log Files
Extract timestamp or message strings strictly from server log lines flagged with 'ERROR'.
Python
server_logs = [
    "INFO: Server started successfully",
    "ERROR: Database connection timeout",
    "WARNING: High memory usage detected",
    "ERROR: Unauthorized API request token"
]

# Extract text description from error logs only
error_messages = [log.replace("ERROR: ", "") for log in server_logs if log.startswith("ERROR")]

print("Extracted Error Messages:")
for msg in error_messages:
    print(f" - {msg}")
Output: Extracted Error Messages: - Database connection timeout - Unauthorized API request token
Real-Time Example 5: Applying Conditional Logic (If-Else Expression)
Classify exam scores or student results as 'Pass' or 'Fail' inline during list creation.
Python
student_scores = [45, 82, 38, 91, 60, 74]

# Label each score using conditional expression (if score >= 50 else 'Fail')
score_grades = ["Pass" if score >= 50 else "Fail" for score in student_scores]

print("Student Scores:", student_scores)
print("Result Status: ", score_grades)
Output: Student Scores: [45, 82, 38, 91, 60, 74] Result Status: ['Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass']
Real-Time Example 6: Flattening Nested Matrix (2D to 1D)
Flatten a 2D matrix or table grid into a single linear list using nested loops in comprehension.
Python
matrix_grid = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Flatten 2D grid into 1D list
flattened_list = [num for row in matrix_grid for num in row]

print("2D Matrix Grid:", matrix_grid)
print("Flattened 1D List:", flattened_list)
Output: 2D Matrix Grid: [[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: Transforming Retail Inventory Pricing
Apply automated discount calculations across wholesale product prices in a single instruction.
Python
original_prices = [1000, 2500, 500, 4000]

# Apply a 10% festive discount and round off
discounted_prices = [round(price * 0.90, 2) for price in original_prices]

print("Original Prices (₹):", original_prices)
print("Discounted Prices (₹):", discounted_prices)
Output: Original Prices (₹): [1000, 2500, 500, 4000] Discounted Prices (₹): [900.0, 2250.0, 450.0, 3600.0]
Real-Time Example 8: Extracting Specific Object Attributes
Extract specific values from a list of dictionaries representing database records.
Python
employees = [
    {"name": "Amit", "department": "Engineering"},
    {"name": "Priya", "department": "Marketing"},
    {"name": "Rahul", "department": "Engineering"}
]

# Extract names of employees working exclusively in Engineering
eng_staff = [emp["name"] for emp in employees if emp["department"] == "Engineering"]

print("Engineering Department Staff:", eng_staff)
Output: Engineering Department Staff: ['Amit', 'Rahul']
Real-Time Example 9: Generating Multiplication Tables
Quickly build mathematical multiplication tables or data matrix values programmatically.
Python
# Generate table of 7 up to 10 multiples
table_of_seven = [7 * i for i in range(1, 11)]

print("Multiplication Table of 7:")
print(table_of_seven)
Output: Multiplication Table of 7: [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]

Summary of Python List Comprehension

  • Concise Syntax: Replaces bulky multi-line loops with elegant single-line expressions: [expr for item in iterable if condition].
  • High Efficiency: Faster execution speed compared to standard for loops and append() methods.
  • Versatile Use: Perfect for filtering items, transforming strings, flattening 2D matrices, parsing logs, and formatting datasets.