List comprehension is a concise, elegant way to create new lists based on existing lists or iterables. It is one of the most "Pythonic" features because it allows you to replace multiple lines of for loops and append() calls with a single line.
The Basic Syntax
The logic is written inside square brackets: [expression for item in iterable if condition]
Expression: What you want to do with the item (the result).
Item: The variable representing the current element.
Iterable: The source (list, range, etc.).
Condition: (Optional) A filter to decide if the item should be included.
# --- Traditional Way (4 lines) ---
numbers = [1, 2, 3, 4, 5, 6]
squares = []
for n in numbers:
if n % 2 == 0:
squares.append(n * n)
# --- List Comprehension Way (1 line) ---
# "Give me n squared for every n in numbers if n is even"
new_squares = [n * n for n in numbers if n % 2 == 0]
print(f"Original: {numbers}")
print(f"Squares of even numbers: {new_squares}")
# Transforming strings
names = ["alice", "bob", "charlie"]
cap_names = [name.upper() for name in names]
print(cap_names) # ['ALICE', 'BOB', 'CHARLIE']Benefits of List Comprehensions
Readability: Once you are used to the syntax, it is much easier to read at a glance.
Performance: List comprehensions are generally faster than manual loops because they are optimized internally by the Python interpreter.
Space: It reduces boilerplate code, making your files smaller and cleaner.