What is map()?
map() applies a function to every element of an iterable and returns the results.
Without map() (the old way):
numbers = [1, 2, 3, 4, 5]
doubled = []
for num in numbers:
doubled.append(num * 2)
print(doubled) # [2, 4, 6, 8, 10]
With map() (elegant!):
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
One line instead of a loop! 🚀
map() syntax
map(function, iterable)
Parameters:
- function — what to apply to each element
- iterable — a list, tuple, string, etc.
Returns: A map object (convert to a list to use it)
result = map(func, data) # map object
result_list = list(map(func, data)) # list
Basic examples
1. Multiply by 2
numbers = [1, 2, 3, 4, 5]
# With a lambda
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
# With a regular function
def double(x):
return x * 2
doubled2 = list(map(double, numbers))
print(doubled2) # [2, 4, 6, 8, 10]
2. Square each element
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # [1, 4, 9, 16, 25]
3. Type conversion
# String to int
strings = ["1", "2", "3", "4", "5"]
numbers = list(map(int, strings))
print(numbers) # [1, 2, 3, 4, 5]
# Int to string
numbers = [10, 20, 30]
strings = list(map(str, numbers))
print(strings) # ['10', '20', '30']
# Float to int
floats = [1.5, 2.7, 3.9]
integers = list(map(int, floats))
print(integers) # [1, 2, 3] (truncates the fractional part!)
map() with strings
String transformations
words = ["python", "javascript", "go"]
# Uppercase
upper_words = list(map(str.upper, words))
print(upper_words) # ['PYTHON', 'JAVASCRIPT', 'GO']
# Word lengths
lengths = list(map(len, words))
print(lengths) # [6, 10, 2]
# First letter
first_letters = list(map(lambda w: w[0], words))
print(first_letters) # ['p', 'j', 'g']
Formatting
names = ["alice", "bob", "carl"]
# Capitalize
capitalized = list(map(str.capitalize, names))
print(capitalized) # ['Alice', 'Bob', 'Carl']
# Add a prefix
with_prefix = list(map(lambda n: f"Student: {n}", names))
print(with_prefix) # ['Student: alice', 'Student: bob', 'Student: carl']
map() with dictionaries
Extracting values
students = [
{"name": "Alice", "grade": 95},
{"name": "Bob", "grade": 87},
{"name": "Carl", "grade": 92}
]
# Extract names
names = list(map(lambda s: s["name"], students))
print(names) # ['Alice', 'Bob', 'Carl']
# Extract grades
grades = list(map(lambda s: s["grade"], students))
print(grades) # [95, 87, 92]
Transforming the structure
students = [
{"name": "Alice", "grade": 95},
{"name": "Bob", "grade": 87}
]
# Add a status field
with_status = list(map(
lambda s: {**s, "status": "Honors" if s["grade"] >= 90 else "Passing"},
students
))
print(with_status)
# [
# {"name": "Alice", "grade": 95, "status": "Honors"},
# {"name": "Bob", "grade": 87, "status": "Passing"}
# ]
map() with multiple iterables
map() can accept multiple iterables!
numbers1 = [1, 2, 3]
numbers2 = [10, 20, 30]
# Element-wise addition
sums = list(map(lambda x, y: x + y, numbers1, numbers2))
print(sums) # [11, 22, 33]
# Element-wise multiplication
products = list(map(lambda x, y: x * y, numbers1, numbers2))
print(products) # [10, 40, 90]
Note: If the iterables have different lengths, map() stops at the shortest one!
short = [1, 2]
long = [10, 20, 30, 40]
result = list(map(lambda x, y: x + y, short, long))
print(result) # [11, 22] (only 2 elements!)
Practical examples
Example 1: Normalizing data
# Data in 0–1 range, need 0–100
data = [0.1, 0.5, 0.75, 0.9]
normalized = list(map(lambda x: x * 100, data))
print(normalized) # [10.0, 50.0, 75.0, 90.0]
# Rounded
rounded = list(map(lambda x: round(x * 100), data))
print(rounded) # [10, 50, 75, 90]
Example 2: Processing prices
prices = [100, 200, 150, 300]
# Apply a 20% discount
discounted = list(map(lambda p: p * 0.8, prices))
print(discounted) # [80.0, 160.0, 120.0, 240.0]
# Add 10% tax
with_tax = list(map(lambda p: p * 1.1, prices))
print(with_tax) # [110.0, 220.0, 165.0, 330.0]
Example 3: Building URLs
products = ["phone", "laptop", "mouse"]
# Create a URL for each product
urls = list(map(lambda p: f"https://shop.com/products/{p}", products))
for url in urls:
print(url)
# https://shop.com/products/phone
# https://shop.com/products/laptop
# https://shop.com/products/mouse
map() vs List Comprehension
Both accomplish the same thing!
numbers = [1, 2, 3, 4, 5]
# map()
doubled_map = list(map(lambda x: x * 2, numbers))
# List comprehension
doubled_comp = [x * 2 for x in numbers]
print(doubled_map == doubled_comp) # True
When to use which?
map() — when:
- ✅ You already have a named function
- ✅ The transformation is simple
- ✅ You prefer a functional style
# map is cleaner here
numbers = ["1", "2", "3"]
integers = list(map(int, numbers))
List comprehension — when:
- ✅ You need a condition (if)
- ✅ The logic is more complex
- ✅ You prefer the Pythonic style
# Comprehension is cleaner here
numbers = [1, 2, 3, 4, 5]
even_doubled = [x * 2 for x in numbers if x % 2 == 0]
Chaining map() calls
You can apply map() multiple times!
numbers = [1, 2, 3, 4, 5]
# Multiply by 2, then square
result = list(map(lambda x: x ** 2, map(lambda x: x * 2, numbers)))
print(result) # [4, 16, 36, 64, 100]
# Read right to left:
# 1. Multiply by 2: [2, 4, 6, 8, 10]
# 2. Square: [4, 16, 36, 64, 100]
But this is clearer:
# Easier to read and understand!
doubled = list(map(lambda x: x * 2, numbers))
squared = list(map(lambda x: x ** 2, doubled))
print(squared) # [4, 16, 36, 64, 100]
Common mistakes
Mistake 1: Forgot list()
numbers = [1, 2, 3]
result = map(lambda x: x * 2, numbers)
print(result) # <map object at 0x...> ← NOT a list!
# ✅ CORRECT
result = list(map(lambda x: x * 2, numbers))
print(result) # [2, 4, 6]
Mistake 2: Function doesn’t return a value
def double_bad(x):
x * 2 # Missing return!
result = list(map(double_bad, [1, 2, 3]))
print(result) # [None, None, None] ← Bug!
# ✅ CORRECT
def double_good(x):
return x * 2
result = list(map(double_good, [1, 2, 3]))
print(result) # [2, 4, 6]
Mistake 3: Expecting the original list to change
# map does NOT modify the original list!
numbers = [1, 2, 3]
doubled = list(map(lambda x: x * 2, numbers))
print(numbers) # [1, 2, 3] ← unchanged!
print(doubled) # [2, 4, 6] ← new list
Performance
map() is faster than a for loop on large datasets!
import time
data = list(range(1000000)) # One million numbers
# With a for loop
start = time.time()
result1 = []
for x in data:
result1.append(x * 2)
time_for = time.time() - start
# With map
start = time.time()
result2 = list(map(lambda x: x * 2, data))
time_map = time.time() - start
print(f"For: {time_for:.4f}s")
print(f"Map: {time_map:.4f}s")
# map is typically 10–30% faster!
Combining with other functions
map + filter
numbers = [1, 2, 3, 4, 5, 6]
# Double only the even numbers
result = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, numbers)))
print(result) # [4, 8, 12]
map + sorted
words = ["python", "go", "javascript"]
# Sort by length, then uppercase
result = list(map(str.upper, sorted(words, key=len)))
print(result) # ['GO', 'PYTHON', 'JAVASCRIPT']
map + reduce
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# Double each, then sum
doubled = map(lambda x: x * 2, numbers)
total = reduce(lambda acc, x: acc + x, doubled, 0)
print(total) # 30
Summary
map() is:
- ✅ Applying a function to every element
- ✅ Returns a new iterable
- ✅ Does NOT modify the original
- ✅ Faster than a for loop
- ✅ Functional programming style
Syntax:
list(map(function, data))
Typical usage:
# Type conversion
list(map(int, ["1", "2", "3"]))
# With a lambda
list(map(lambda x: x * 2, numbers))
# With a named function
list(map(str.upper, words))
# Multiple iterables
list(map(lambda x, y: x + y, list1, list2))
What’s next?
Now you know map()! 🎉
Next topics:
- filter() — select elements matching a condition
- reduce() — fold a list down to a single value
- List comprehensions — an alternative to map
map() is a cornerstone of functional programming! 🚀
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!