map()
function applies a given function to each item of an iterable (like a list, tuple, etc.) and returns a map object (which is an iterator).map(function, iterable)
Parameter | Description |
---|---|
function |
A function to apply to each element |
iterable |
A sequence (like list, tuple, string, etc.) |
nums = [1, 2, 3, 4]
doubled = map(lambda x: x * 2, nums)
print(list(doubled)) # Output: [2, 4, 6, 8]
def square(n):
return n ** 2
numbers = [1, 2, 3, 4]
result = map(square, numbers)
print(list(result)) # Output: [1, 4, 9, 16]
map()
with Multiple Iterablesa = [1, 2, 3]
b = [4, 5, 6]
result = map(lambda x, y: x + y, a, b)
print(list(result)) # Output: [5, 7, 9]
str_nums = ['1', '2', '3']
int_nums = list(map(int, str_nums))
print(int_nums) # Output: [1, 2, 3]
map()
and List ComprehensionFeature | map() |
List Comprehension |
---|---|---|
Readability | Better with built-in functions | Better for simple expressions |
Speed | Slightly faster for large data | Often more readable |
Flexibility | Less (single function) | More (supports conditions, etc.) |
# Both do the same
list(map(lambda x: x*2, [1, 2, 3]))
[ x*2 for x in [1, 2, 3] ]
map()
returns a map object, so convert it using list()
, tuple()
, etc., to see results.
Best used with lambda functions or built-in functions.
Cannot directly handle complex logic (like nested loops or multiple conditions).
Less readable than list comprehension for beginners.