Python

Python List Comprehension

List comprehension provides a short and readable way to create a new list from an existing iterable.

Instead of writing multiple lines using a for loop, we can often create the same list in a single line.

Basic Syntax

[expression for item in iterable]

For example:

numbers = [1, 2, 3, 4, 5]

squares = [x * x for x in numbers]

print(squares)

Output:

[1, 4, 9, 16, 25]

Here:

  • x * x → expression
  • x → current item
  • numbers → iterable
  • [] → creates a new list

1. Basic List Comprehension

Suppose we want to create a list containing numbers from 1 to 5.

Using a normal loop:

numbers = []

for x in range(1, 6):
    numbers.append(x)

print(numbers)

Output:

[1, 2, 3, 4, 5]

The same thing using list comprehension:

numbers = [x for x in range(1, 6)]

print(numbers)

Output:

[1, 2, 3, 4, 5]

List comprehension makes the code shorter.

2. Create Squares

numbers = [1, 2, 3, 4, 5]

squares = [x ** 2 for x in numbers]

print(squares)

Output:

[1, 4, 9, 16, 25]

3. Create Cubes

numbers = [1, 2, 3, 4, 5]

cubes = [x ** 3 for x in numbers]

print(cubes)

Output:

[1, 8, 27, 64, 125]

4. Multiply Every Number

numbers = [10, 20, 30, 40]

result = [x * 2 for x in numbers]

print(result)

Output:

[20, 40, 60, 80]

5. Convert Strings to Uppercase

List comprehension also works with strings.

names = ["ram", "sita", "hari", "gita"]

result = [name.upper() for name in names]

print(result)

Output:

['RAM', 'SITA', 'HARI', 'GITA']

6. Convert Strings to Lowercase

names = ["RAM", "SITA", "HARI", "GITA"]

result = [name.lower() for name in names]

print(result)

Output:

['ram', 'sita', 'hari', 'gita']

7. Get String Lengths

names = ["Ram", "Sita", "Hari", "Rajendra"]

lengths = [len(name) for name in names]

print(lengths)

Output:

[3, 4, 4, 7]

8. List Comprehension with a Condition

List comprehension can include an if condition.

Syntax

[expression for item in iterable if condition]

Example:

numbers = [1, 2, 3, 4, 5, 6]

even_numbers = [
    x for x in numbers
    if x % 2 == 0
]

print(even_numbers)

Output:

[2, 4, 6]

9. Get Odd Numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8]

odd_numbers = [
    x for x in numbers
    if x % 2 != 0
]

print(odd_numbers)

Output:

[1, 3, 5, 7]

10. Get Numbers Greater Than 50

numbers = [20, 45, 60, 75, 30, 90]

result = [
    x for x in numbers
    if x > 50
]

print(result)

Output:

[60, 75, 90]

11. Get Positive Numbers

numbers = [-5, 10, -3, 20, 0, -8, 15]

positive_numbers = [
    x for x in numbers
    if x > 0
]

print(positive_numbers)

Output:

[10, 20, 15]

12. Get Negative Numbers

numbers = [-5, 10, -3, 20, 0, -8, 15]

negative_numbers = [
    x for x in numbers
    if x < 0
]

print(negative_numbers)

Output:

[-5, -3, -8]

13. Filter Strings by Length

names = ["Ram", "Sita", "Hari", "Raj", "Anita"]

result = [
    name for name in names
    if len(name) > 3
]

print(result)

Output:

['Sita', 'Hari', 'Anita']

14. Names Starting With a Specific Letter

names = ["Ram", "Raj", "Sita", "Ramesh", "Hari"]

result = [
    name for name in names
    if name.startswith("R")
]

print(result)

Output:

['Ram', 'Raj', 'Ramesh']

15. Names Ending With a Specific Letter

names = ["Ram", "Sita", "Hari", "Gita", "Raj"]

result = [
    name for name in names
    if name.endswith("a")
]

print(result)

Output:

['Sita', 'Gita']

16. List Comprehension with range()

We can directly use range().

numbers = [x for x in range(1, 11)]

print(numbers)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

17. Even Numbers from range()

even_numbers = [
    x for x in range(1, 21)
    if x % 2 == 0
]

print(even_numbers)

Output:

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

18. Squares of Even Numbers

We can combine an expression and a condition.

numbers = [1, 2, 3, 4, 5, 6]

result = [
    x ** 2
    for x in numbers
    if x % 2 == 0
]

print(result)

Output:

[4, 16, 36]

The process is:

2 → 2² → 4
4 → 4² → 16
6 → 6² → 36

19. List Comprehension with if-else

List comprehensions can also use if-else.

Syntax

[expression_if_true if condition else expression_if_false for item in iterable]

Example:

numbers = [1, 2, 3, 4, 5]

result = [
    "Even" if x % 2 == 0 else "Odd"
    for x in numbers
]

print(result)

Output:

['Odd', 'Even', 'Odd', 'Even', 'Odd']

Notice the difference between filtering and conditional expressions.

With only if

[x for x in numbers if x % 2 == 0]

This removes values that don't satisfy the condition.

With if-else

["Even" if x % 2 == 0 else "Odd" for x in numbers]

This keeps every value but changes what is produced.

20. Convert Numbers to Even/Odd Labels

numbers = [10, 15, 20, 25, 30]

result = [
    "Even" if x % 2 == 0 else "Odd"
    for x in numbers
]

print(result)

Output:

['Even', 'Odd', 'Even', 'Odd', 'Even']

21. Nested List Comprehension

List comprehensions can contain more than one for loop.

Example

result = [
    (x, y)
    for x in [1, 2, 3]
    for y in [10, 20]
]

print(result)

Output:

[(1, 10), (1, 20), (2, 10), (2, 20), (3, 10), (3, 20)]

This is equivalent to:

result = []

for x in [1, 2, 3]:
    for y in [10, 20]:
        result.append((x, y))

print(result)

22. Create Multiplication Table

We can use nested list comprehension.

table = [
    x * y
    for x in range(1, 6)
    for y in range(1, 6)
]

print(table)

Output:

[1, 2, 3, 4, 5, 2, 4, 6, 8, 10, 3, 6, 9, 12, 15, 4, 8, 12, 16, 20, 5, 10, 15, 20, 25]

23. Flatten a Nested List

Suppose we have:

numbers = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

We can flatten it:

result = [
    number
    for row in numbers
    for number in row
]

print(result)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

24. List Comprehension with Dictionary

We can create a list from dictionary data.

students = {
    "Ram": 75,
    "Sita": 85,
    "Hari": 35,
    "Gita": 90
}

names = [
    name
    for name in students
]

print(names)

Output:

['Ram', 'Sita', 'Hari', 'Gita']

25. Filter Dictionary Data

We can also use a condition.

students = {
    "Ram": 75,
    "Sita": 85,
    "Hari": 35,
    "Gita": 90
}

top_students = [
    name
    for name, marks in students.items()
    if marks >= 80
]

print(top_students)

Output:

['Sita', 'Gita']

26. Create a Dictionary with Dictionary Comprehension

List comprehension creates lists.

Python also provides dictionary comprehension for creating dictionaries.

numbers = [1, 2, 3, 4, 5]

squares = {
    x: x ** 2
    for x in numbers
}

print(squares)

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

The basic syntax is:

{key: value for item in iterable}

27. Dictionary Comprehension with Condition

numbers = [1, 2, 3, 4, 5, 6]

even_squares = {
    x: x ** 2
    for x in numbers
    if x % 2 == 0
}

print(even_squares)

Output:

{2: 4, 4: 16, 6: 36}

28. Set Comprehension

Comprehensions can also create sets.

numbers = [1, 2, 2, 3, 3, 4, 5]

squares = {
    x ** 2
    for x in numbers
}

print(squares)

Output:

{1, 4, 9, 16, 25}

Duplicate values are automatically removed because the result is a set.

29. List Comprehension vs map()

The same operation can often be performed using either approach.

Using map()

numbers = [1, 2, 3, 4, 5]

result = list(
    map(lambda x: x ** 2, numbers)
)

print(result)

Using List Comprehension

numbers = [1, 2, 3, 4, 5]

result = [
    x ** 2
    for x in numbers
]

print(result)

Both produce:

[1, 4, 9, 16, 25]

For straightforward transformations, list comprehensions are often more readable.

30. List Comprehension vs filter()

Using filter()

numbers = [1, 2, 3, 4, 5, 6]

result = list(
    filter(lambda x: x % 2 == 0, numbers)
)

print(result)

Using List Comprehension

numbers = [1, 2, 3, 4, 5, 6]

result = [
    x
    for x in numbers
    if x % 2 == 0
]

print(result)

Both produce:

[2, 4, 6]

31. Practical Example : Student Results

students = [
    {"name": "Raj", "marks": 85},
    {"name": "John", "marks": 35},
    {"name": "Sita", "marks": 91},
    {"name": "Hari", "marks": 42}
]

passed_students = [
    student["name"]
    for student in students
    if student["marks"] >= 40
]

print(passed_students)

Output:

['Raj', 'Sita', 'Hari']

32. Practical Example : Product Prices

products = [
    {"name": "Laptop", "price": 80000},
    {"name": "Mouse", "price": 1500},
    {"name": "Keyboard", "price": 3000},
    {"name": "Monitor", "price": 25000}
]

expensive_products = [
    product["name"]
    for product in products
    if product["price"] > 20000
]

print(expensive_products)

Output:

['Laptop', 'Monitor']

33. Practical Example : Data Processing

List comprehensions are frequently useful when processing data.

temperatures = [20, 25, 30, 35, 40]

fahrenheit = [
    (temp * 9 / 5) + 32
    for temp in temperatures
]

print(fahrenheit)

Output:

[68.0, 77.0, 86.0, 95.0, 104.0]

Important Points to Remember

  1. List comprehension is a concise way to create a new list.
  2. Basic syntax:
[expression for item in iterable]
  1. A condition can be added:
[expression for item in iterable if condition]
  1. if-else can also be used:
[expression_if_true if condition else expression_if_false for item in iterable]
  1. List comprehensions can work with lists, tuples, sets, dictionaries, strings, range(), and other iterables.
  2. Nested list comprehensions can contain multiple for clauses.
  3. Dictionary and set comprehensions are also available.
  4. List comprehensions are especially useful for simple transformations and filtering.

Easy way to remember

List Comprehension → Create a list quickly

Basic:

[x for x in numbers]

With transformation:

[x * 2 for x in numbers]

With filtering:

[x for x in numbers if x > 10]

With if-else:

["Even" if x % 2 == 0 else "Odd" for x in numbers]
Interactive Sandbox
Python