← Back to all snippets
PYTHON

Transform and Filter Lists with List Comprehensions

Efficiently transform, filter, and create new lists in Python using concise list comprehensions for clean and readable data manipulation.

# Basic transformation (mapping)
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x**2 for x in numbers]
print(f"Squared numbers: {squared_numbers}")

# Basic filtering
even_numbers = [x for x in numbers if x % 2 == 0]
print(f"Even numbers: {even_numbers}")

# Transformation and filtering combined
odd_squares = [x**2 for x in numbers if x % 2 != 0]
print(f"Odd squares: {odd_squares}")

# Nested list comprehension to flatten
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [num for row in matrix for num in row]
print(f"Flattened matrix: {flattened_list}")

# Conditional expressions within list comprehension
parity_check = ["even" if x % 2 == 0 else "odd" for x in numbers]
print(f"Parity check: {parity_check}")
How it works: List comprehensions provide a concise way to create lists. They can be used to map (transform) elements, filter elements based on a condition, or combine both operations. They are generally more readable and often more performant than traditional `for` loops or `map()` and `filter()` functions, especially for simple transformations. They also support nested structures for flattening and conditional expressions for inline logic.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs