List Comprehensions let you build lists in a concise way. There are also dictionary and set comprehensions.
📝 Syntax:
• List: [expression for item in iterable if condition]
• Dict: {key: value for item in iterable}
• Set: {expression for item in iterable}
python
# List comprehension
squares = [x**2 for x in range(10)]
print(f"Squares: {squares}")
# With condition
evens = [x for x in range(20) if x % 2 == 0]
print(f"Evens: {evens}")
# Nested comprehension
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(f"Matrix: {matrix}")
# Dictionary comprehension
square_dict = {x: x**2 for x in range(1, 6)}
print(f"Dict: {square_dict}")
# Set comprehension
unique_lengths = {len(word) for word in ["hello", "world", "python"]}
print(f"Lengths: {unique_lengths}")You should see
Squares: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Evens: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] Matrix: [[1, 2, 3], [2, 4, 6], [3, 6, 9]] Dict: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} Lengths: {5, 6}