Category: python
Understanding map()
Published on 27 Oct 2026
Explanation
map() applies a function to each item and returns an iterator in Python 3.
Code:
numbers = [1, 2, 3, 4] print(list(map(str, numbers)))
Explanation
Pass an existing function to map() to transform each input value lazily.
Code:
def square(n): return n*n print(list(map(square, [1, 2, 3, 4])))
Explanation
A list comprehension directly builds a list and is often easy to read for simple transformations.
Code:
numbers = [1, 2, 3, 4, 5] print([n*n for n in numbers])
Explanation
A comprehension can combine transformation and filtering in one expression.
Code:
numbers = [1, 2, 3, 4, 5, 6] result = [n*n for n in numbers if n % 2 == 0] print(result)
Explanation
Use map() when applying an existing function is clear; use comprehensions for concise transformations with conditions.
Code:
prices = [100, 200, 300] def add_tax(price): return price * 1.18 print(list(map(add_tax, prices))) print([p * 1.18 for p in prices])