List comprehension in Python provides a concise way to create lists. It allows developers to write code that is shorter, more readable, and often more efficient than traditional loops.
List comprehension is a syntactic construct that allows creating a new list by applying an expression to each element in an iterable, often with a condition.
[expression for item in iterable if condition]
Expression: The operation or transformation applied to each item.
Iterable: The source sequence (e.g., a list, range, or string).
Condition (optional): A filter to include only certain elements.
numbers = [x for x in range(10)]
print(numbers)
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
squares = [x**2 for x in range(10)]
print(squares)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)
# Output: [0, 2, 4, 6, 8]
words = ['hello', 'world', 'python']
uppercase_words = [word.upper() for word in words]
print(uppercase_words)
# Output: ['HELLO', 'WORLD', 'PYTHON']
matrix = [[x for x in range(3)] for _ in range(3)]
print(matrix)
# Output: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Concise and Readable – Reduces the number of lines of code.
Faster Execution – More efficient than traditional loops.
Less Memory Usage – Creates lists directly instead of using loops with append()
.
List comprehension is a powerful feature in Python that improves code readability and efficiency. It is widely used in data manipulation, filtering, and transformations. By mastering list comprehension, you can write more elegant and Pythonic code.