Learn Python list comprehension with clear syntax, beginner-friendly examples, and real-world applications. Discover how to write concise, efficient code for data processing, filtering, and transformations.
List comprehension is a concise way to create lists in Python. It provides a compact syntax for transforming or filtering data from one list (or any iterable) to another. Instead of using a traditional for
loop with .append()
, you can often express list operations more elegantly with list comprehension.
for
loops in many cases.[expression for item in iterable if condition]
expression
: What you want to do with each itemitem
: The variable representing each element in the iterableiterable
: The sequence you’re looping through (list, tuple, string, etc.)condition
(optional): Filters which items to include# Traditional way
numbers = [1, 2, 3, 4]
squares = []
for num in numbers:
squares.append(num ** 2)
# With list comprehension
squares = [num ** 2 for num in numbers]
# Result: [1, 4, 9, 16]
# Only even numbers
numbers = [1, 2, 3, 4, 5, 6]
evens = [num for num in numbers if num % 2 == 0]
# Result: [2, 4, 6]
# Squares of even numbers only
numbers = [1, 2, 3, 4, 5, 6]
even_squares = [num ** 2 for num in numbers if num % 2 == 0]
# Result: [4, 16, 36]
# Convert comma-separated string to list of integers
user_input = "1, 2, 3, 4, five, 6"
numbers = [int(x.strip()) for x in user_input.split(',') if x.strip().isdigit()]
# Result: [1, 2, 3, 4, 6]
# Remove empty strings and strip whitespace
data = [" apple ", "banana", " ", "cherry ", ""]
clean_data = [fruit.strip() for fruit in data if fruit.strip()]
# Result: ["apple", "banana", "cherry"]
# Read lines from a file and remove newline characters
with open('data.txt') as file:
lines = [line.strip() for line in file]
# Transpose a matrix (swap rows and columns)
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed = [[row[i] for row in matrix] for i in range(3)]
# Result: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# Extract specific fields from API response
api_response = [
{"id": 1, "name": "Alice", "active": True},
{"id": 2, "name": "Bob", "active": False},
{"id": 3, "name": "Charlie", "active": True}
]
active_users = [user["name"] for user in api_response if user["active"]]
# Result: ["Alice", "Charlie"]
While list comprehensions are powerful, they’re not always the best choice:
In these cases, a traditional for
loop might be more appropriate.
List comprehension examples: https://youtube.com/shorts/cnSLqqx_huQ?si=5J19IZzT23VvtDmp