Episode 22 of 29
Maps
Learn how to use the map() function to apply transformations to sequences.
The map() function applies a function to every item in an iterable.
Basic Map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]Map with Named Functions
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
temps_c = [0, 20, 37, 100]
temps_f = list(map(celsius_to_fahrenheit, temps_c))
print(temps_f) # [32.0, 68.0, 98.6, 212.0]Map vs List Comprehension
Both achieve similar results. List comprehensions are generally more Pythonic and readable.