0
0
PythonHow-ToBeginner · 3 min read

How to Use map Function in Python: Syntax and Examples

The map function in Python applies a given function to each item of an iterable (like a list) and returns a map object with the results. You use it by passing the function and the iterable as arguments, then convert the result to a list or another iterable type if needed.
📐

Syntax

The map function has this basic syntax:

  • map(function, iterable)

Here, function is the operation you want to apply to each item, and iterable is the collection of items (like a list or tuple).

The result is a map object, which you can convert to a list or loop over.

python
map(function, iterable)
💻

Example

This example shows how to use map to square each number in a list:

python
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)
print(list(squared))
Output
[1, 4, 9, 16, 25]
⚠️

Common Pitfalls

One common mistake is forgetting that map returns a map object, not a list. If you try to print it directly, you get a memory address instead of the values.

Also, using a function that does not accept the right number of arguments will cause errors.

python
numbers = [1, 2, 3]
result = map(lambda x: x + 1, numbers)
print(result)  # Wrong: prints map object

print(list(result))  # Right: prints [2, 3, 4]
Output
map object at 0x7f8c1b2d9d60 [2, 3, 4]
📊

Quick Reference

PartDescription
functionThe function to apply to each item
iterableThe collection of items to process
map objectThe result, which can be converted to list or iterated

Key Takeaways

Use map to apply a function to every item in an iterable easily.
Remember to convert the map object to a list to see the results.
The function passed to map must accept one argument per iterable item.
You can use lambda for quick inline functions with map.
Multiple iterables can be passed to map if the function accepts multiple arguments.