Python – List Comprehensions

A basic list comprehensions follows this format: [result for singular-element in list-name].

If we’d like to filter objects, then we need to use the if keyword:

numbers = [13, 4, 18, 35]
# Instead of: filter(lambda num: num % 5 == 0, numbers),
# we can do:
div_by_5 = [num for num in numbers if num % 5 == 0]

print(div_by_5) # [35]

# We can manage the combined case as well:
# Instead of: 
# map(lambda num: num ** 2
# , filter(lambda num: num % 2 == 0
# , range(1, 21)))
# we can do:
arbitrary_numbers = [num ** 2 for num in range(1, 21) if num % 2 == 0]
print(arbitrary_numbers)
# [4, 16, 36, ...]

Every map and filter expression can be expressed as a list comprehension.

Leave a Reply