What is List Comprehension in Python?
List comprehension is a concise and efficient way to create lists in Python. It replaces traditional for
loops with a single-line expression, making code more readable and faster.
Why Use List Comprehension?
✅ More readable and compact than for
loops
✅ Improves performance by reducing iterations
✅ Makes code more Pythonic
Basic Syntax of List Comprehension
new_list = [expression for item in iterable if condition]
Breakdown:
expression
: The operation to apply on each itemitem
: The current element in the iterationiterable
: The list, range, or other iterable being processedif condition
: (Optional) Filters items based on a condition
Step-by-Step Guide for List Comprehension in Python with Examples
1. Creating a List with List Comprehension
✅ Example: Generate a list of squares
squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]
💡 Best Practice: Keep it simple. Avoid overly complex expressions inside the comprehension.
2. Filtering Elements with a Condition
✅ Example: Get even numbers from a list
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]
💡 Best Practice: Use filtering conditions wisely to improve readability.
3. Using List Comprehension with Strings
✅ Example: Convert a list of words to uppercase
words = ["hello", "world", "python"]
uppercase_words = [word.upper() for word in words]
print(uppercase_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
💡 Best Practice: Use built-in string methods like .upper()
, .lower()
, etc., for text transformations.
4. Using if-else
in List Comprehension
✅ Example: Replace negative numbers with 0
numbers = [-3, -1, 2, -5, 4]
modified_numbers = [0 if x < 0 else x for x in numbers]
print(modified_numbers) # Output: [0, 0, 2, 0, 4]
💡 Best Practice: Keep the if-else
expression simple for better readability.
5. Nested List Comprehension
✅ Example: Flatten a 2D list
matrix = [[1, 2], [3, 4], [5, 6]]
flattened = [num for row in matrix for num in row]
print(flattened) # Output: [1, 2, 3, 4, 5, 6]
💡 Best Practice: Use nested comprehension only when necessary. Otherwise, consider using loops for clarity.
6. List Comprehension with Functions
✅ Example: Apply a function to each element
def square(x):
return x ** 2
numbers = [1, 2, 3, 4]
squared_numbers = [square(x) for x in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16]
💡 Best Practice: If logic is complex, define a function separately instead of using inline expressions.
Performance Comparison: List Comprehension vs for Loop
✅ Example: Squaring numbers using for
loop vs list comprehension
import time
# Using for loop
start = time.time()
squares_loop = []
for x in range(1, 1000000):
squares_loop.append(x**2)
end = time.time()
print(f"Loop time: {end - start:.5f} seconds")
# Using list comprehension
start = time.time()
squares_comp = [x**2 for x in range(1, 1000000)]
end = time.time()
print(f"List comprehension time: {end - start:.5f} seconds")
💡 Best Practice: List comprehensions are generally faster and should be preferred for large data processing.
Best Practices for List Comprehension in Python
✔ Use list comprehension for simple and readable operations.
✔ Avoid deep nesting – use loops when logic is complex.
✔ Use if-else
wisely for better readability.
✔ Apply functions within comprehension for reusable code.