Python – Combine map, lambda, and filter functions

# Let's arbitrarily get the all numbers
# divisible by 3 between 1 and 20 and
# cube them.
arbitrary_numbers = map(lambda num: num ** 2,
filter(lambda num: num % 3 == 0,
range(1, 21)))

print(list(arbitrary_numbers))
# [27, 216, 729, 1728, 3375, 5832]

The expression in arbitrary_numbers can be broken down to 3 parts:

  • range(1, 21)ย is an iterable object representing numbers from 1, 2, 3, 4… 19, 20.
  • filter(lambda num: num % 2 == 0, range(1, 21))ย is an iterator for the number sequence 2, 4, 6, …
  • When they’re squared by theย mapย expression we can get an iterator for the number sequence 4, 16, 36, …

Leave a Reply