List comprehension is a concise and elegant way to create lists in Python. With list comprehensions, you can generate a new list from one or more iterable objects (such as lists, tuples, strings, sets, etc.), while filtering and transforming elements during the generation process. List comprehensions not only make code more concise, but also improve readability and execution efficiency.
Basic Syntax
The basic syntax of a list comprehension is as follows:
[表达式 for 元素 in 可迭代对象 if 条件]
- Expression: It is the operation or transformation you want to perform on each element.
- Element: Represents the element currently being iterated.
- Iterable object: The object you want to iterate over, such as a list, tuple, string, etc.
- Condition(Optional): A filtering condition. Only elements that meet the condition will be included in the resulting list.
Basic Examples
The following are some examples of list comprehensions.
Generate a list of square numbers
Example
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Generate a list of even numbers
Example
print(evens) # Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Generate the uppercase form of each character in a string:
Example
print(uppercase_chars) # Output: ['H', 'E', 'L', 'L', 'O']
3. Nested Loops
List comprehensions can also contain nested loops to handle multi-dimensional data structures or generate combinations. For example:
Example
print(cartesian_product) # Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
Processing a matrix
Example
flatten = [elem for row in matrix for elem in row]
print(flatten) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
4. Conditional Filtering
You can add conditions to a list comprehension to filter out elements that do not satisfy the condition.
Filter out negative numbers
Example
positive_numbers = [x for x in numbers if x >= 0]
print(positive_numbers) # Output: [0, 2, 4, 6]
Filter and transform
Example
capitalized_words = [word.capitalize() for word in words if len(word) > 5]
print(capitalized_words) # Output: ['Banana', 'Cherry']
5. Complex Expressions
List comprehensions are not limited to simple expressions and conditions; you can perform more complex operations in the expression:
Multi-condition filtering and transformation
Example
result = [x**2 if x % 2 == 0 else x**3 for x in numbers if x > 0]
print(result) # Output: [1, 4, 27, 16, 125, 36, 343, 64, 729]
Using functions
Example
return x**2
squares = [square(x) for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
6. Notes
- Readability: Although list comprehensions can make code more concise, overly complex list comprehensions can affect readability. In such cases, using a regular loop may be better.
- Performance: List comprehensions are more efficient than regular loops in most cases, but when dealing with very large datasets, generator expressions may be a better choice because they do not generate the entire list at once, but generate elements on demand.