List Comprehension

List Comprehension in Python: One of the most loved features of Python is the List Comprehension.

Concept Explanation

One of the most loved features of Python is the List Comprehension. It allows you to create a new list based on an existing one using a single, readable line of code.

Instead of writing a 3 or 4-line for loop to filter or transform data, you can pack that logic into the list definition itself. It's not just "syntactic sugar"—it is often faster and more efficient than a traditional loop because Python's internal engine is optimized for this specific pattern.


Syntax or Core Structure

The Basic Formula

[expression for item in iterable if condition]

  1. Expression: What you want to put into the new list (the result).
  2. Item: The variable name for the current element.
  3. Iterable: The source list, range, or string.
  4. Condition (Optional): A filter to decide if the item should be included.
# Traditional Way
squares = []
for x in range(5):
    squares.append(x**2)

# List Comprehension Way
squares = [x**2 for x in range(5)]
# Result: [0, 1, 4, 9, 16]

Code Example #1 (Basic)

Filtering a list of names to only include those starting with 'A'.

names = ["Alice", "Bob", "Amanda", "Charlie", "Alex"]

# Only keep names that start with "A"
a_names = [name for name in names if name.startswith("A")]

print(f"Original: {names}")
print(f"Filtered: {a_names}")

Code Example #2 (Intermediate)

Performing transformations and filtering at the same time.

prices = [100, 250, 45, 10, 500]

# Give a 10% discount to items over $100
# Expression: price * 0.9
# Condition: if price > 100
discounted_high_value = [p * 0.9 for p in prices if p > 100]

print(f"Special offers: {discounted_high_value}")

Real World Example

Imagine you are cleaning a list of email addresses that came from a messy user form. Some have extra spaces, and some are in all caps. You need to standardize them.

# 📧 Data Cleaning Automation
raw_emails = [" HARSH@gmail.com ", "test@User.com", "  ALICE@example-site.org"]

# Step 1: Strip whitespace
# Step 2: Convert to lowercase
clean_emails = [email.strip().lower() for email in raw_emails]

print("Standardized Emails:")
for email in clean_emails:
    print(f"- {email}")

Common Mistakes

  1. Making it Too Complex: If your list comprehension is more than one line long or has multiple nested loops, it becomes hard to read. In those cases, a regular for loop is better.
  2. Forgetting the Expression: Beginners often forget that the FIRST part of the comprehension defines what goes into the list. [item for item in list] is the simplest form.
  3. Performance on Massive Data: While fast, list comprehensions create the entire list in memory at once. If you're dealing with 10 million items, you might want to use a Generator Expression (which uses () instead of []) to save RAM.

Best Practices

  • Readability First: If your colleague can't understand what the line does in 2 seconds, break it down.
  • Use as a Filter: It is the most "Pythonic" way to remove None values or empty strings from a dataset: [x for x in data if x].

Practice Exercises

  1. Uppercase conversion: Given a list of cities ["new york", "london", "paris"], use a list comprehension to create a new list where every city is in ALL CAPS.
  2. Even squares: Create a list of squares for all EVEN numbers between 1 and 20. (Hint: Use range(1, 21) and an if condition).
  3. Character count: Given a list of words, create a new list that contains the length of each word.