# Basic comprehension
squares = [x**2for x inrange(10)]
print(squares)
# With filter
evens = [x for x inrange(20) if x % 2 == 0]
print(evens)
# Nested comprehension (matrix)
matrix = [[i * j for j inrange(1, 4)] for i inrange(1, 4)]
for row in matrix:
print(row)
# Dict comprehension
word = "mississippi"
freq = {ch: word.count(ch) for ch inset(word)}
print(freq)
Output
Click "Run" to execute your code
Comprehensions are syntactic sugar for common for-loop-and-append patterns. They are often faster because the append is optimized internally.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?