Python Basics — map() Function

3 minute read

The map() Function

map() applies a function to every item in an iterable and returns an iterator of results. It’s a clean way to transform data without writing explicit loops.

Syntax

map(function, iterable)
map(function, iterable1, iterable2, ...)

Basic Usage

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

# Square each number
squared = map(lambda x: x ** 2, numbers)
print(list(squared))  # [1, 4, 9, 16, 25]

map() returns an iterator (lazy), not a list. Wrap in list() to see all results.

Mapping with Named Functions

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

temperatures_c = [0, 20, 37, 100]
temperatures_f = list(map(celsius_to_fahrenheit, temperatures_c))
print(temperatures_f)  # [32.0, 68.0, 98.6, 212.0]

Mapping with Lambda

names = ["alice", "bob", "charlie"]

# Capitalize each name
capitalized = list(map(lambda n: n.capitalize(), names))
print(capitalized)  # ['Alice', 'Bob', 'Charlie']

# String lengths
lengths = list(map(lambda n: len(n), names))
print(lengths)  # [5, 3, 7]

Using Built-in Functions with map()

# Convert strings to integers
str_numbers = ["1", "2", "3", "4", "5"]
int_numbers = list(map(int, str_numbers))
print(int_numbers)  # [1, 2, 3, 4, 5]

# Convert to uppercase using method reference
words = ["hello", "world", "python"]
upper_words = list(map(str.upper, words))
print(upper_words)  # ['HELLO', 'WORLD', 'PYTHON']

# Absolute values
values = [-3, -1, 0, 2, 5]
abs_values = list(map(abs, values))
print(abs_values)  # [3, 1, 0, 2, 5]

Multiple Iterables with map()

When you pass multiple iterables, the function receives one argument from each:

# Add corresponding elements
a = [1, 2, 3]
b = [10, 20, 30]

sums = list(map(lambda x, y: x + y, a, b))
print(sums)  # [11, 22, 33]

# Format full names
firsts = ["Alice", "Bob", "Charlie"]
lasts = ["Smith", "Jones", "Brown"]

full_names = list(map(lambda f, l: f"{f} {l}", firsts, lasts))
print(full_names)  # ['Alice Smith', 'Bob Jones', 'Charlie Brown']

When iterables have different lengths, map() stops at the shortest:

a = [1, 2, 3, 4, 5]
b = [10, 20, 30]

result = list(map(lambda x, y: x + y, a, b))
print(result)  # [11, 22, 33] — stops at shortest

map() vs List Comprehension

Feature map() List Comprehension
Syntax map(func, iterable) [func(x) for x in iterable]
Returns Iterator (lazy) List (eager)
Filtering No (needs filter()) Built-in with if
Readability Good for simple transforms Better for most cases
Speed Slightly faster for built-in funcs Similar performance
numbers = [1, 2, 3, 4, 5]

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

# List comprehension — more Pythonic
result2 = [x ** 2 for x in numbers]

print(result1)  # [1, 4, 9, 16, 25]
print(result2)  # [1, 4, 9, 16, 25]

General rule: Prefer list comprehensions for most cases. Use map() when passing an existing named function (like int, str.upper, etc.) for cleaner code.

Practical Examples

Processing Dictionaries

students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78},
]

names = list(map(lambda s: s["name"], students))
print(names)  # ['Alice', 'Bob', 'Charlie']

# Add grade to each student
def add_grade(student):
    score = student["score"]
    grade = "A" if score >= 90 else ("B" if score >= 80 else "C")
    return {**student, "grade": grade}

graded = list(map(add_grade, students))
for s in graded:
    print(s)
# {'name': 'Alice', 'score': 85, 'grade': 'B'}
# {'name': 'Bob', 'score': 92, 'grade': 'A'}
# {'name': 'Charlie', 'score': 78, 'grade': 'C'}

Chaining map() Calls

raw_data = ["  Alice  ", "  BOB  ", "  charlie  "]

# Strip whitespace, then capitalize
cleaned = list(map(str.capitalize, map(str.strip, raw_data)))
print(cleaned)  # ['Alice', 'Bob', 'Charlie']

Summary

  • map(func, iterable) applies func to every item
  • Returns an iterator — wrap in list() to see results
  • Works with lambdas, named functions, and built-in functions
  • Supports multiple iterables — stops at the shortest
  • Prefer list comprehensions for most Python code
  • Use map() when the function already exists (e.g., int, str.upper)

Next up: filter() Function →

Updated: