List comprehension is a powerful and concise feature in Python for creating lists. It provides a compact way to generate new lists based on existing lists or other iterable objects.
The basic syntax of a list comprehension is:
[expression for item in iterable if condition]
This syntax combines a for
loop with an optional conditional statement, all within square brackets.
Let's create a list of squares for numbers from 0 to 9:
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
You can add conditions to filter elements. Here's an example that creates a list of even squares:
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # Output: [0, 4, 16, 36, 64]
for
loopsList comprehensions can be used with multiple for
loops and conditions:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
While list comprehensions are powerful, sometimes other approaches might be more appropriate:
map()
or filter()
List comprehensions offer a concise and efficient way to create lists in Python. They're particularly useful for simple transformations and filtering operations. However, it's important to balance conciseness with readability, especially in more complex scenarios.
By mastering list comprehensions, you'll be able to write more elegant and efficient Python code, enhancing your overall programming skills.