Some text some message..
Back 13 🧠 What is map() in Python? 25 Jun, 2025

The 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).


✅ Syntax

map(function, iterable)
Parameter Description
function A function to apply to each element
iterable A sequence (like list, tuple, string, etc.)

🔸 Example: Double each number in a list

nums = [1, 2, 3, 4]
doubled = map(lambda x: x * 2, nums)
print(list(doubled))  # Output: [2, 4, 6, 8]

🔸 Example with Named Function

def square(n):
    return n ** 2

numbers = [1, 2, 3, 4]
result = map(square, numbers)
print(list(result))  # Output: [1, 4, 9, 16]

🔸 Using map() with Multiple Iterables

a = [1, 2, 3]
b = [4, 5, 6]

result = map(lambda x, y: x + y, a, b)
print(list(result))  # Output: [5, 7, 9]

🧪 Real-World Use Case: Convert string numbers to integers

str_nums = ['1', '2', '3']
int_nums = list(map(int, str_nums))
print(int_nums)  # Output: [1, 2, 3]

🔄 Difference Between map() and List Comprehension

Feature 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] ]

💡 Notes

  • map() returns a map object, so convert it using list(), tuple(), etc., to see results.

  • Best used with lambda functions or built-in functions.


⚠️ Limitations

  • Cannot directly handle complex logic (like nested loops or multiple conditions).

  • Less readable than list comprehension for beginners.