List Comprehension Tasks in Python
List comprehension is one of Python’s most powerful and elegant features. It lets you create new lists from existing ones in a single, readable line of code.
Basic Syntax
# [expression for item in iterable if condition]
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Squares of Even Numbers
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # Output: [4, 16, 36, 64, 100]
Filter Strings by Length
words = ["cat", "elephant", "dog", "hippopotamus", "ox"]
long_words = [w for w in words if len(w) > 4]
print(long_words) # Output: ['elephant', 'hippopotamus']
Convert to Uppercase
fruits = ["apple", "banana", "cherry"]
upper_fruits = [f.upper() for f in fruits]
print(upper_fruits) # Output: ['APPLE', 'BANANA', 'CHERRY']
Flatten a 2D List
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Dictionary Comprehension Bonus
nums = [1, 2, 3, 4, 5]
squared_dict = {n: n**2 for n in nums}
print(squared_dict) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Key Takeaway
List comprehensions are faster than equivalent for-loops and more readable. Master the pattern [expression for item in iterable if condition] — it appears in almost every Python codebase.
(Visited 21 times, 1 visits today)