List Comprehension in Python: A Complete Guide with Examples

Learn how to use list comprehension in Python to write concise, readable code. Understand its syntax, benefits, and practical use cases.

List Comprehension in Python: A Complete Guide with Examples
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.
What is List Comprehension?
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.
Syntax of List Comprehension
[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.
Examples of List Comprehension
1. Creating a List from a Range
numbers = [x for x in range(10)]
print(numbers)
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Squaring Numbers in a List
squares = [x**2 for x in range(10)]
print(squares)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
3. Filtering Even Numbers
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)
# Output: [0, 2, 4, 6, 8]
4. Converting Strings to Uppercase
words = ['hello', 'world', 'python']
uppercase_words = [word.upper() for word in words]
print(uppercase_words)
# Output: ['HELLO', 'WORLD', 'PYTHON']
5. Nested List Comprehension (Creating a Matrix)
matrix = [[x for x in range(3)] for _ in range(3)]
print(matrix)
# Output: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
Advantages of Using List Comprehension
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()
.
Conclusion
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.