Python List Comprehension


Python list comprehension provides a compact way to create a new list from an iterable such as another list, range(), string, tuple, or other sequence.

A list comprehension combines an expression with a for loop inside square brackets. A condition can also be added when only selected values are required.

List comprehensions are useful when the operation is simple and can be expressed clearly in one statement.

Syntax of List Comprehension 🔝

The basic syntax is:

[expression for item in iterable]

A condition can be added:

[expression for item in iterable if condition]

The expression produces the value that is added to the new list.

Basic List Comprehension Example 🔝

The following list comprehension creates a list containing the squares of numbers from 0 through 4.

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

print(squares)
Output
[0, 1, 4, 9, 16]

For every value produced by range(5), the expression x**2 is evaluated and the result is added to the new list.

List Comprehension vs for Loop 🔝

The same list can be created using a normal for loop and append().

Using a for Loop

squares=[]

for x in range(5):
    squares.append(x**2)

print(squares)
Output
[0, 1, 4, 9, 16]

Using List Comprehension

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

print(squares)

Both examples produce the same list. The list comprehension expresses the transformation in a shorter form.

For complex logic containing several statements, a normal loop can be easier to read.

List Comprehension with a Condition 🔝

An if condition can be placed after the for clause to include only values that match a condition.

Here we create a list containing only even numbers.

even_numbers=[
    x
    for x in range(10)
    if x % 2 == 0
]

print(even_numbers)
Output
[0, 2, 4, 6, 8]

The expression adds x only when the remainder after division by 2 is 0.

Squares of Even Numbers

We can combine filtering and transformation in the same list comprehension.

even_squares=[
    x**2
    for x in range(10)
    if x % 2 == 0
]

print(even_squares)
Output
[0, 4, 16, 36, 64]

Using if-else in List Comprehension 🔝

An if-else expression can be used when every input value should produce an output, but the output depends on a condition.

result=[
    'Even' if x % 2 == 0 else 'Odd'
    for x in range(1, 6)
]

print(result)
Output
['Odd', 'Even', 'Odd', 'Even', 'Odd']

Notice the position of the condition:

value_if_true if condition else value_if_false

This conditional expression appears before the for clause.

Creating a New List from an Existing List 🔝

List comprehension is commonly used to transform the elements of an existing list.

numbers=[2, 4, 6, 8]

new_list=[
    x * 10
    for x in numbers
]

print(new_list)
print(numbers)
Output
[20, 40, 60, 80]
[2, 4, 6, 8]

The list comprehension creates a new list. The original numbers list remains unchanged.

List Comprehension with Strings 🔝

Strings can also be processed using list comprehension.

Finding the Length of Each String

names=[
    'Alex',
    'Ronald',
    'John'
]

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

print(lengths)
Output
[4, 6, 4]

The len() function is applied to every string.

Converting Strings to Uppercase

names=[
    'alex',
    'ronald',
    'john'
]

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

print(upper_names)
Output
['ALEX', 'RONALD', 'JOHN']

Filtering Strings

The following example keeps only names beginning with 'A'.

names=[
    'Alex',
    'Ronald',
    'Anil',
    'John'
]

result=[
    name
    for name in names
    if name.startswith('A')
]

print(result)
Output
['Alex', 'Anil']

Using a Function in List Comprehension 🔝

A user-defined function can be called for each element of a list comprehension.

def double_value(x):
    return x * 2

numbers=[1, 2, 3, 4]

result=[
    double_value(x)
    for x in numbers
]

print(result)
Output
[2, 4, 6, 8]

The function is called once for each value in numbers.

List Comprehension with Two for Loops 🔝

More than one for clause can be used in a list comprehension.

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

print(pairs)
Output
[(1, 10), (1, 20), (2, 10), (2, 20)]

The second loop runs for every value produced by the first loop.

This is equivalent to:

pairs=[]

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

print(pairs)

Creating a 2D List 🔝

Nested list comprehension can create a 2D list.

my_list=[
    [
        j
        for j in range(3)
    ]
    for i in range(3)
]

print(my_list)
Output
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

The inner comprehension creates one row. The outer comprehension creates three separate rows.

Creating a Matrix of Zeros

rows=3
cols=4

matrix=[
    [
        0
        for j in range(cols)
    ]
    for i in range(rows)
]

print(matrix)
Output
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Each row is created separately, so changing one row does not automatically change the others.

Flattening a 2D List 🔝

List comprehension can convert a nested list into a single flat list.

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

flat_list=[
    item
    for row in my_list
    for item in row
]

print(flat_list)
Output
[1, 2, 3, 4, 5, 6]

The outer loop reads each row, and the inner loop reads each item from that row.

Filtering Values from a 2D List 🔝

A condition can also be added while flattening a 2D list.

This example collects only values greater than 3.

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

result=[
    item
    for row in my_list
    for item in row
    if item > 3
]

print(result)
Output
[4, 5, 6]

List Comprehension vs map() 🔝

Both list comprehension and the map() function can apply an operation to every element.

Using List Comprehension

numbers=[1, 2, 3, 4]

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

print(squares)
Output
[1, 4, 9, 16]

Using map()

def square(x):
    return x**2

numbers=[1, 2, 3, 4]

squares=list(
    map(square, numbers)
)

print(squares)
Output
[1, 4, 9, 16]

List comprehension is often convenient when the transformation can be expressed directly. map() is useful when an existing function should be applied to every item.

List Comprehension vs filter() 🔝

Both list comprehension and the filter() function can select matching elements.

Using List Comprehension

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

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

print(even)
Output
[2, 4, 6]

Using filter()

def is_even(x):
    return x % 2 == 0

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

even=list(
    filter(is_even, numbers)
)

print(even)
Output
[2, 4, 6]

Use the form that makes the logic easiest to understand for the program being written.

Common List Comprehension Mistakes 🔝

1. Putting a Filtering if Before the for Clause

When if is used only to filter values, it appears after the for clause.

Correct:
even=[
    x
    for x in range(10)
    if x % 2 == 0
]

2. Confusing Filtering with if-else

A filtering condition appears after the loop:

[
    x
    for x in numbers
    if x > 0
]

A conditional expression that chooses between two output values appears before the loop:

[
    'Positive' if x > 0 else 'Zero or Negative'
    for x in numbers
]

3. Making the Comprehension Too Complex

List comprehension is useful for compact transformations and filtering, but shorter code is not always clearer code.

When the logic requires several conditions, statements, or intermediate calculations, a normal for loop can be easier to understand and maintain.

Summary of List Comprehension 🔝

  • List comprehension creates a new list from an iterable.
  • The basic form is [expression for item in iterable].
  • Add if condition after the loop to filter values.
  • Use value1 if condition else value2 before the loop when every item must produce a result.
  • List comprehension can transform values from an existing list.
  • Functions and string methods can be used in the expression.
  • Multiple for clauses can be used for nested loops.
  • Nested list comprehensions can create 2D lists.
  • A 2D list can be flattened using two for clauses.
  • List comprehension can often replace simple loops using append().
  • map() and filter() provide alternative approaches for transformations and filtering.
  • For complex logic, a normal loop can be easier to read.
Python List for Loop filter() map() 2D List




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer