Python map()
Function
The map() function lets you apply a function to each item in a list, tuple, or any other iterable — all in one line. It's a very handy tool for data transformation and functional programming.
Syntax
map(function, iterable)
Parameters:
function
– A function to apply to each element of the iterable.iterable
– A sequence (like a list, tuple, or string) whose items you want to process.
Returns:
- A
map
object (an iterator), which you can convert to a list or loop through.
Example: Square Numbers in a List
numbers = [1, 2, 3, 4]
squared = map(lambda x: x * x, numbers)
print(list(squared))
[1, 4, 9, 16]
Example: Convert Strings to Uppercase
words = ["apple", "banana", "cherry"]
uppercase_words = map(str.upper, words)
print(list(uppercase_words))
['APPLE', 'BANANA', 'CHERRY']
Use Case: Clean and Transform Data
Imagine you have a list of prices as strings and want to convert them to floats:
prices = ["10.5", "20.99", "5.00"]
prices_float = map(float, prices)
print(list(prices_float))
[10.5, 20.99, 5.0]
Using map()
with Multiple Iterables
You can also use map()
with two or more iterables:
a = [1, 2, 3]
b = [4, 5, 6]
sum_values = map(lambda x, y: x + y, a, b)
print(list(sum_values))
[5, 7, 9]
Common Mistakes
- Forgetting to convert the map object:
map()
returns an iterator, not a list by default. - Not using a function: You must pass a valid function or lambda.
- Mismatch in length: If using multiple iterables,
map()
stops at the shortest one.
Interview Tip
map()
is often used to clean or transform datasets in one line. It shows functional programming skills and saves you from writing verbose for
loops.
Summary
map()
applies a function to each item of an iterable.- Returns a
map
object (an iterator). - Often used with
lambda
for quick transformations. - Works with multiple iterables too.
Practice Problem
Write a program that takes a list of numbers and returns a new list with the cube of each number using map()
.
nums = [2, 3, 4]
cubes = map(lambda x: x**3, nums)
print(list(cubes))