Definition of the map() function in Python
The map() function is a built-in Python function that allows you to apply a function to each element of one or more iterables (such as a list, a tuple, or a set). It returns a map object, which is itself a lazy iterator, meaning it only computes results when they are requested.
If you follow our complete Python course, you will discover that map() is one of the fundamental functions of functional programming in Python, alongside filter() and reduce(). Understanding map() will allow you to write more concise, more readable, and often more performant code.
The map() function never modifies the original iterable. It creates a new object containing the results of the transformation applied to each element.
Syntax of map()
The syntax of the map() function is very simple:
map(function, iterable, ...)It takes at least two arguments:
- function: the function to apply to each element. It can be a regular function defined with def, a lambda function, or any other callable.
- iterable: one or more iterables whose elements will be passed to the function.
The return value is a map object that you can convert to a list, tuple, or any other collection type.
# Basic syntax
result = map(function, iterable)
# With multiple iterables
result = map(function, iterable1, iterable2)
# Convert to list to see results
result_list = list(map(function, iterable))Practical examples of map()
Example 1: Applying a simple function
The most common use of map() is to apply a transformation to each element of a list. Let's start with a simple example: squaring each number in a list.
# Define a transformation function
def square(x):
return x ** 2
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Apply map()
result = map(square, numbers)
# Convert to list to display
print(list(result)) # [1, 4, 9, 16, 25]Here, the square() function is applied to each element of the numbers list. The result is a new object containing the transformed values.
Example 2: Using map() with a lambda function
For simple transformations, it is common to use a lambda function directly in map(). This avoids defining a separate function for a trivial operation.
# Convert temperatures from Celsius to Fahrenheit
celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: c * 9/5 + 32, celsius))
print(fahrenheit) # [32.0, 68.0, 98.6, 212.0]Example 3: Transforming strings
map() is particularly useful for manipulating strings, for example to uppercase them, clean them, or format them.
# Uppercase a list of first names
names = ["alice", "bob", "charlie", "diana"]
names_upper = list(map(str.upper, names))
print(names_upper) # ['ALICE', 'BOB', 'CHARLIE', 'DIANA']
# Strip unnecessary whitespace
data = [" Paris ", " Lyon", "Marseille "]
clean_data = list(map(str.strip, data))
print(clean_data) # ['Paris', 'Lyon', 'Marseille']When you pass a method like str.upper without parentheses, Python understands that you are referring to the function itself, not its result.
Example 4: Using map() with multiple iterables
The map() function can accept multiple iterables. In this case, the function passed as the first argument must accept as many parameters as there are iterables. The iteration stops as soon as the shortest iterable is exhausted (similar behavior to zip).
# Add two lists element by element
list_a = [1, 2, 3, 4]
list_b = [10, 20, 30, 40]
sums = list(map(lambda a, b: a + b, list_a, list_b))
print(sums) # [11, 22, 33, 44]
# With three iterables
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
result = list(map(lambda a, b, c: a + b + c, x, y, z))
print(result) # [12, 15, 18]Example 5: Type conversion with map()
A very common use case is type conversion. For example, transforming a list of strings into a list of integers.
# Convert strings to integers
strings = ["1", "2", "3", "4", "5"]
integers = list(map(int, strings))
print(integers) # [1, 2, 3, 4, 5]
# Convert integers to strings
numbers = [10, 20, 30]
strings = list(map(str, numbers))
print(strings) # ['10', '20', '30']
# Convert user input
user_input = "3 7 12 25 8"
values = list(map(int, user_input.split()))
print(values) # [3, 7, 12, 25, 8]Warning: if one of the elements cannot be converted (for example int("abc")), a ValueError exception will be raised. Make sure to handle these cases in your code.
Example 6: map() with complex custom functions
You can use map() with more elaborate functions, especially to transform data structures like dict.
# Transform a list of dictionaries
users = [
{"last_name": "Dupont", "first_name": "Jean", "age": 30},
{"last_name": "Martin", "first_name": "Marie", "age": 25},
{"last_name": "Bernard", "first_name": "Luc", "age": 35},
]
def format_user(user):
return f"{user['first_name']} {user['last_name']} ({user['age']} years old)"
full_names = list(map(format_user, users))
print(full_names)
# ['Jean Dupont (30 years old)', 'Marie Martin (25 years old)', 'Luc Bernard (35 years old)']Notice the use of f-string to format strings elegantly.
map() vs list comprehension
In Python, list comprehensions often offer an alternative to map(). Let's look at the differences:
| Criteria | map() | List comprehension |
|---|---|---|
| Readability | Good with named functions | Better for simple expressions |
| Performance | Slightly faster with native C functions | Slightly faster with lambdas |
| Lazy evaluation | Yes (returns an iterator) | No (creates the list immediately) |
| Filtering | No (requires filter()) | Yes (built-in if clause) |
| Multiple iterables | Yes, natively | Requires zip() |
Here is a code comparison:
numbers = [1, 2, 3, 4, 5]
# With map()
result_map = list(map(lambda x: x ** 2, numbers))
# With list comprehension
result_lc = [x ** 2 for x in numbers]
# Both give: [1, 4, 9, 16, 25]
print(result_map == result_lc) # TrueAs a general rule, prefer list comprehensions when the transformation is simple and fits on one line. Use map() when you already have a named function to apply or when you are working with multiple iterables.
Lazy evaluation of map()
A fundamental aspect of map() is that it returns a lazy iterator. This means that elements are only computed when they are consumed. This is a major advantage when working with large amounts of data.
# map() doesn't compute anything immediately
result = map(lambda x: x ** 2, range(1_000_000))
print(result) # <map object at 0x...>
# Elements are computed on demand
for value in result:
if value > 100:
print(f"First value > 100: {value}")
break
# First value > 100: 121
# Only the first 11 elements were computed!Warning: a map object can only be consumed once. Once iterated over, it is exhausted. If you need to reuse the results, convert it to a list or a tuple.
# Demonstrating iterator exhaustion
result = map(lambda x: x * 2, [1, 2, 3])
print(list(result)) # [2, 4, 6]
print(list(result)) # [] ← the iterator is exhausted!Advanced use cases
Combining map() with other functions
You can chain map() with other functions like filter(), zip, or enumerate to create powerful data transformation pipelines.
# Chaining map() and filter()
numbers = range(1, 21)
# Step 1: keep only even numbers (filter)
# Step 2: square them (map)
result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))
print(result) # [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]Using map() with classes
Since map() accepts any callable, you can use it with class constructors to create object instances.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
# Create points from coordinates
coords_x = [1, 2, 3, 4]
coords_y = [10, 20, 30, 40]
points = list(map(Point, coords_x, coords_y))
print(points) # [Point(1, 10), Point(2, 20), Point(3, 30), Point(4, 40)]map() with None as function
In Python 2, passing None as the function to map() was equivalent to using zip. In Python 3, this syntax is no longer supported and will raise a TypeError.
# Python 3 - This does NOT work
# map(None, [1, 2, 3]) # TypeError: 'NoneType' object is not callable
# Use zip() directly instead
result = list(zip([1, 2, 3], ['a', 'b', 'c']))
print(result) # [(1, 'a'), (2, 'b'), (3, 'c')]Best practices with map()
Here are the essential recommendations for using map() effectively in your Python projects:
- Prefer named functions: if your lambda becomes too complex (more than one expression), define a function with def to keep your code readable.
- Don't forget the conversion:
map()returns an iterator, not a list. Uselist(),tuple(), or iterate over it with a loop if you need concrete results. - Prefer list comprehensions for simple cases:
[x * 2 for x in numbers]is often more readable thanlist(map(lambda x: x * 2, numbers)). - Leverage lazy evaluation: when working with large amounts of data, don't unnecessarily convert the result to a list.
- Use built-in functions:
map(int, list)ormap(str.strip, list)are cases wheremap()shines with its conciseness. - Document your transformations: add comment or docstring to explain complex transformations.
Frequently asked questions
What is the difference between map() and a for loop in Python?
The map() function applies a transformation to each element of an iterable in a declarative way, while a for loop is imperative. map() returns a lazy iterator, making it more memory efficient for large datasets. Additionally, map() is generally more concise and can be slightly faster when using native C functions (like int, str, len). However, a for loop offers more flexibility for complex logic involving conditions or side effects.
Can you use map() with a dictionary?
Yes, but you should know that when you pass a dict to map(), the iteration is done over the keys of the dictionary by default. To iterate over values, use dict.values(), and for key-value pairs, use dict.items(). For example: list(map(str.upper, my_dict.keys())) will transform all keys to uppercase.
Does map() modify the original list?
No, map() never modifies the original iterable. It creates a new map object containing the results of the transformation. This is consistent behavior with the principles of functional programming, where data is immutable. If you want to modify the original list, you will need to reassign the result: my_list = list(map(transformation, my_list)).
How can I learn to master map() and functional programming in Python?
To master map() and all functional programming concepts in Python, regular practice is essential. We recommend following our dedicated Python course on Believemy, which covers in detail built-in functions like map(), filter(), and reduce(), with many practical exercises to consolidate your skills.