In Python, we often need to create lists. For example, generating the squares of numbers from 1 to 10 or filtering even numbers from a list. If we use traditional for loops and the append() method, the code can be quite verbose. Is there a simpler way? The answer is: List Comprehensions!
What is a List Comprehension?¶
A list comprehension is a concise way to create lists in Python. It allows us to complete loops and element processing in a single line of code, generating a new list. In short, it achieves list creation with fewer lines of code.
Why Use List Comprehensions?¶
Let’s take an example: to generate the squares of numbers from 1 to 10, the traditional method requires a loop and append():
# Traditional method
squares = []
for i in range(1, 11): # Loop from 1 to 10
squares.append(i ** 2) # Calculate square and add to the list
print(squares) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
With a list comprehension, it only takes one line:
# List comprehension
squares = [i ** 2 for i in range(1, 11)]
print(squares) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Benefits: The code is more concise and readable. You avoid repeating append(), and the list is created in one line.
Basic Syntax Structure¶
The core format of a list comprehension is:
[expression for variable in iterable]
- Expression: Operations performed on the variable (e.g.,
i**2,i*2, string processing). The result becomes an element of the list. - Variable: Each element in the loop (e.g.,
i, any valid variable name). - Iterable: An object that can be looped over (e.g.,
range(), lists, tuples;range()is common).
List Comprehensions Without Conditions¶
If you only need to uniformly process elements from an iterable (no filtering), use the basic syntax directly.
Example 1: Generate squares of numbers 1 to 10
squares = [i ** 2 for i in range(1, 11)]
print(squares) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Example 2: Generate even multiples of numbers 1 to 5
even_multiples = [i * 2 for i in range(1, 6)] # Multiply each i (1-5) by 2
print(even_multiples) # Output: [2, 4, 6, 8, 10]
List Comprehensions With Conditions¶
To filter elements (e.g., keep only even numbers), add if condition at the end. The format becomes:
[expression for variable in iterable if condition]
Example 3: Filter even numbers from 1 to 10
Traditional method:
evens = []
for i in range(1, 11):
if i % 2 == 0: # Check if even
evens.append(i)
print(evens) # Output: [2, 4, 6, 8, 10]
List comprehension:
evens = [i for i in range(1, 11) if i % 2 == 0]
print(evens) # Output: [2, 4, 6, 8, 10]
Example 4: Filter even numbers greater than 3
result = [i for i in range(1, 11) if i > 3 and i % 2 == 0]
print(result) # Output: [4, 6, 8, 10]
More Flexible Expressions¶
The “expression” in a list comprehension can be any valid Python operation, such as string processing or function calls.
Example 5: Convert names in a list to uppercase
names = ['alice', 'bob', 'charlie']
upper_names = [name.upper() for name in names] # name.upper() is a string method
print(upper_names) # Output: ['ALICE', 'BOB', 'CHARLIE']
Example 6: Take absolute values of numbers in a list
numbers = [-1, 2, -3, 4, -5]
abs_numbers = [abs(num) for num in numbers] # abs() is an absolute value function
print(abs_numbers) # Output: [1, 2, 3, 4, 5]
Note: List Comprehensions vs Generator Expressions¶
- List Comprehensions: Use
[]and generate a complete list, which occupies memory. - Generator Expressions: Use
()and generate a “lazy sequence” (iterated on-demand), saving memory. Beginners should first master list comprehensions.
Summary¶
The core advantage of list comprehensions is conciseness and efficiency, making code more compact and readable. By comparing traditional loops with list comprehensions, you’ll see they drastically reduce code length.
Practice Suggestion: Try rewriting previous for loop + append() code with list comprehensions, such as generating cubes of numbers 1 to 20 or filtering negative numbers from a list. With more practice, you’ll master this style quickly!