List Comprehensions | Dataplexa

List Comprehensions in Python

List Comprehension is one of the most powerful and elegant features of Python. It allows you to create new lists in a clean, short, and readable way — often replacing long loops with a single compact line.

For beginners, list comprehensions may look confusing at first, but after understanding the pattern, they become extremely easy and enjoyable to use. They also make your programs faster and more professional.

What Is a List Comprehension?

A list comprehension is a concise way to create lists. Instead of using multiple lines with a loop, we can generate a list in just one line.

Basic Pattern:

[expression for item in iterable]

To understand it simply:
expression → what to do with each item
item → variable holding each element
iterable → list, string, range, etc.

Why Use List Comprehensions?

They provide several advantages:

  • Cleaner and shorter syntax
  • Better performance than normal loops
  • Easy to read once familiar
  • Perfect for data transformation tasks

Example 1: Create a List of Squares

Traditional loop method:

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

Now using list comprehension:

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

Both produce the same result, but the second method is cleaner and more professional.

Example 2: Convert All Strings to Uppercase

This is a common real-world requirement when processing names or categories.

names = ["sree", "kiran", "arun"]
upper_names = [name.upper() for name in names]
print(upper_names)

Here the expression name.upper() is applied to each item in the list.

Adding Conditions (List Comprehension with if)

We can filter items while generating a list. This is extremely useful for selecting only the values you need.

Basic pattern:

[expression for item in iterable if condition]

Example 3: Select Even Numbers Only

numbers = [1, 2, 3, 4, 5, 6]
evens = [x for x in numbers if x % 2 == 0]
print(evens)

This returns only numbers that satisfy the condition x % 2 == 0.

Example 4: Add 1 Only to Odd Numbers

This helps in data transformation tasks.

numbers = [10, 11, 12, 13, 14]
new_list = [x + 1 for x in numbers if x % 2 != 0]
print(new_list)

Using if–else in List Comprehensions

You can apply conditions inside the expression itself. This is like writing a mini if–else inside one line.

Pattern:

[expression_if_true if condition else expression_if_false for item in iterable]

Example 5: Label Numbers as Even or Odd

numbers = [1, 2, 3, 4]
labels = ["Even" if x % 2 == 0 else "Odd" for x in numbers]
print(labels)

This returns: ["Odd", "Even", "Odd", "Even"]

Example 6: Extract First Letter of Each Word

This is useful in text processing tasks like generating initials or abbreviations.

words = ["Dataplexa", "Python", "Learning"]
first_letters = [word[0] for word in words]
print(first_letters)

Nested List Comprehensions

You can place a loop inside another loop using list comprehension. This is powerful for working with matrices or nested lists.

Example 7: Create All Pairs of Numbers

pairs = [(x, y) for x in range(3) for y in range(3)]
print(pairs)

Common Use Cases of List Comprehensions

  • Cleaning and transforming data
  • Filtering lists
  • Applying functions to every element
  • Generating mathematical sequences
  • Converting text (upper, lower, trimming)
  • Extracting information from JSON or dictionaries

📝 Practice Exercises


Exercise 1

Create a list of squares for numbers 1 to 10 using list comprehension.

Exercise 2

Given ["apple", "banana", "cherry"], create a list containing the length of each fruit.

Exercise 3

From the list [5, 12, 7, 20, 33], create a list of numbers greater than 10.

Exercise 4

Use list comprehension to replace all vowels in a string with "*".


✅ Practice Answers


Answer 1

squares = [x * x for x in range(1, 11)]
print(squares)

Answer 2

fruits = ["apple", "banana", "cherry"]
lengths = [len(f) for f in fruits]
print(lengths)

Answer 3

numbers = [5, 12, 7, 20, 33]
result = [x for x in numbers if x > 10]
print(result)

Answer 4

text = "dataplexa"
vowels = "aeiou"
masked = ["*" if ch in vowels else ch for ch in text]
print("".join(masked))