map() Function in PythonThe map() function in Python is a built-in function used to apply a specified function to every element of an iterable (such as a list, tuple, or string). It returns an iterator containing the results after applying the function to each element.
The map() function is commonly used when the same operation needs to be performed on multiple elements of a sequence.
map(function, iterable)
Parameters
function A function that defines the operation to be performed on each element.
iterable A sequence such as a list, tuple, or string whose elements will be processed.
Return Value
def square(n):
return n * n
numbers = [1, 2, 3, 4]
result = map(square, numbers)
print(list(result))
Output
[1, 4, 9, 16]
Explanation
square() is applied to every element of the list numbers.map() returns an iterator containing the squared values.map() with a Lambda FunctionA lambda function is an anonymous function used for short operations.
numbers = [1, 2, 3, 4]
result = map(lambda x: x * 2, numbers)
print(list(result))
Output
[2, 4, 6, 8]
Explanation
2.map() applies this operation to every element.map() can also take multiple iterables as arguments.
a = [1, 2, 3]
b = [4, 5, 6]
result = map(lambda x, y: x + y, a, b)
print(list(result))
Output
[5, 7, 9]
Explanation
a and b.numbers = [1, 2, 3, 4]
result = map(str, numbers)
print(list(result))
Output
['1', '2', '3', '4']
Explanation
str() function converts each number into a string.map() vs With map()Without map()
numbers = [1, 2, 3]
result = []
for n in numbers:
result.append(n * 2)
print(result)
With map()
numbers = [1, 2, 3]
result = map(lambda x: x * 2, numbers)
print(list(result))
Advantage
map() makes the code shorter and more efficient.map() does not return a list directly; it returns a map object (iterator).list().Example:
result = map(lambda x: x + 1, [1, 2, 3])
print(result) # map object
print(list(result)) # actual values
prices = [100, 200, 300]
# Add 10% tax to each price
result = map(lambda x: x * 1.10, prices)
print(list(result))
Output
[110.0, 220.0, 330.0]
map() is a built-in Python function used to apply a function to every element of an iterable.