Python List Comprehension

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

Basic Syntax

Python
Create a list of numbers.
numbers = [x for x in range(5)]
print(numbers)

Transform List Values

You can apply an expression to every item while creating the new list.

Python
Create a list containing squares.
numbers = [1, 2, 3, 4]
squares = [x * x for x in numbers]

print(squares)

Filter Values

Add an if condition to include only values that match a condition.

Python
Select only even numbers.
numbers = [1, 2, 3, 4, 5, 6]
even = [x for x in numbers if x % 2 == 0]

print(even)

List Comprehension with Strings

Python
Convert words to uppercase.
names = ["alice", "bob", "charlie"]
upper_names = [name.upper() for name in names]

print(upper_names)

If-Else in List Comprehension

Python
Label numbers as even or odd.
numbers = [1, 2, 3, 4]
result = ["even" if x % 2 == 0 else "odd" for x in numbers]

print(result)

Summary

List comprehensions make common list-building operations concise. Use them for simple transformations and filtering, while traditional loops may be clearer for complex logic.