Using Map

Apply a function to every element without writing a loop

Posted by Syed Zain Raza

map() is a built-in Python function that applies a function to every item in an iterable and returns an iterator of the results. It is one of the core functional programming tools in Python, alongside filter() and reduce().

The syntax

map(function, iterable)

It returns a map object, which is lazy — it does not compute the results until you iterate over it. Wrap it in list() to get all results at once.

Basic example

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
# [1, 4, 9, 16, 25]

The equivalent for loop:

squares = []
for x in numbers:
    squares.append(x ** 2)

map() is more concise and often faster because it avoids the overhead of repeated append() calls.

Using a named function

You can pass any callable, not just a lambda. Named functions make the intent clearer when the transformation is more involved:

def celsius_to_fahrenheit(c):
    return (c * 9/5) + 32

temps_c = [0, 20, 37, 100]
temps_f = list(map(celsius_to_fahrenheit, temps_c))
# [32.0, 68.0, 98.6, 212.0]

Mapping over multiple iterables

map() accepts more than one iterable. The function receives one element from each iterable per call:

a = [1, 2, 3]
b = [10, 20, 30]
result = list(map(lambda x, y: x + y, a, b))
# [11, 22, 33]

This stops at the shortest iterable, so make sure lengths match if you want all elements covered.

Practical data cleaning example

raw_names = ['  alice ', 'BOB', '  Charlie  ']
clean_names = list(map(lambda n: n.strip().title(), raw_names))
# ['Alice', 'Bob', 'Charlie']

Type conversion on lists

A very common use is converting a list of strings from user input or a CSV into numbers:

raw = ['1', '2', '3', '4', '5']
numbers = list(map(int, raw))
# [1, 2, 3, 4, 5]

Here int is the callable — map() calls int(item) for each element.

map() vs list comprehensions

In modern Python, list comprehensions are often preferred for readability:

# map
squares = list(map(lambda x: x ** 2, numbers))

# list comprehension
squares = [x ** 2 for x in numbers]

The comprehension reads more naturally in most cases. Where map() has an advantage is when passing an existing named function — map(int, strings) is cleaner than [int(s) for s in strings]. And because map() returns a lazy iterator, it can be more memory-efficient when chained with other iterators and you never need the full list at once.

Chaining map with other functions

from functools import reduce

numbers = [1, 2, 3, 4, 5]

# Square each number, keep evens, sum them
result = reduce(
    lambda acc, x: acc + x,
    filter(lambda x: x % 2 == 0, map(lambda x: x ** 2, numbers))
)
# squares: [1, 4, 9, 16, 25] -> evens: [4, 16] -> sum: 20

This pipeline style — transform, filter, reduce — is the functional programming pattern that map() was designed to support.