Learn how to use Python's map() function with clear syntax, beginner-friendly examples, and real-world applications. Master data transformation efficiently!
map()
Function: A Beginner’s GuideThe map()
function is a built-in Python function that applies a given function to each item of an iterable (like a list, tuple, etc.) and returns an iterator of the results.
map(function, iterable, ...)
function
: The function to apply to each itemiterable
: The sequence you want to process (list, tuple, etc.)...
: You can actually pass multiple iterables (optional)numbers = [1, 2, 3, 4, 5]
# Double each number
doubled = map(lambda x: x * 2, numbers)
# Convert to list to see the result
print(list(doubled)) # Output: [2, 4, 6, 8, 10]
def square(number):
return number ** 2
numbers = [1, 2, 3, 4, 5]
squared = map(square, numbers)
print(list(squared)) # Output: [1, 4, 9, 16, 25]
Imagine you have a list of temperatures in Celsius from a weather station and need to convert them to Fahrenheit:
# Celsius temperatures
celsius_temps = [0, 10, 20, 30, 40]
# Conversion function
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
# Convert all temperatures
fahrenheit_temps = map(celsius_to_fahrenheit, celsius_temps)
print("Fahrenheit temperatures:", list(fahrenheit_temps))
# Output: Fahrenheit temperatures: [32.0, 50.0, 68.0, 86.0, 104.0]
When getting numerical input from users, it often comes as strings. map()
can help convert them:
# User enters numbers separated by spaces
user_input = "10 20 30 40 50"
# Split into list of strings and convert to integers
numbers = list(map(int, user_input.split()))
print(numbers) # Output: [10, 20, 30, 40, 50]
print("Sum:", sum(numbers)) # Output: Sum: 150
map()
returns an iterator, not a list - you often need to wrap it in list()
to see the resultsmap()
is often used with other functional tools like filter()
and reduce()