What Is List Comprehension in Python?
List comprehension is a concise way to create new lists in Python using a single line of code. It combines the logic of a for loop, and optional conditions, into a clear expression that produces a list. List comprehension makes your code shorter and often more readable than equivalent loops.
Basic List Comprehension Syntax
-
expression — value or operation applied to each item
-
item — variable representing each element
-
iterable — sequence like a list, range, string, etc.
Examples (Input & Output Together)
1. Create a List from Another List
nums = [1, 2, 3, 4, 5] squares = [x * x for x in nums] print(squares) # Output: # [1, 4, 9, 16, 25]This generates a list of squares for each number.
2. List Comprehension with a range()
evens = [x for x in range(1, 11) if x % 2 == 0] print(evens) # Output: # [2, 4, 6, 8, 10]Here we include a condition to select only even numbers.
List Comprehension with Condition
nums = [1, 2, 3, 4, 5, 6] greater_than_three = [x for x in nums if x > 3] print(greater_than_three) # Output: # [4, 5, 6]The list includes only values greater than 3.
Nested List Comprehension
You can use a list comprehension inside another to produce combinations
pairs = [(i, j) for i in [1, 2, 3] for j in ["a", "b"]] print(pairs) # Output: # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]This creates every pair of (number, letter).
Conditional Expression Inside Comprehension
You can use a ternary expression to modify values conditionally
nums = [1, 2, 3, 4, 5] labels = ["even" if x % 2 == 0 else "odd" for x in nums] print(labels) # Output: # ['odd', 'even', 'odd', 'even', 'odd']Each item is labeled based on parity.
List Comprehension with Strings
You can also create lists from strings
chars = [ch.upper() for ch in "hello"] print(chars) # Output: # ['H', 'E', 'L', 'L', 'O']Here, each character is converted to uppercase.
Why Use List Comprehension?
-
Concise: Replace multi-line loops with one line.
-
Readable: Express list transformations clearly.
-
Efficient: Often faster than loops due to optimized implementation.
List Comprehension vs Loop
Using a loop
nums = [1, 2, 3] squares = [] for x in nums: squares.append(x * x) print(squares) # Output: # [1, 4, 9]Using a list comprehension
squares = [x * x for x in nums] print(squares) # Output: # [1, 4, 9]Both produce the same result, but comprehension is more concise.
Important Notes
-
Conditions in comprehensions filter elements.
-
Nested comprehensions create combinations.
-
Comprehensions can include expressions and function calls.
-
Overly complex comprehensions may hurt readability — use wisely.