Transforming Data with map()
map() applies a function to every element of a sequence, returning a new sequence with the results.
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)
print(list(squared)) # [1, 4, 9, 16, 25]
Think of it as: "transform each item according to this rule." You're not changing the original list, you're creating a new one.
The first argument is a function that takes one input and returns one output. The second is your sequence. map() returns an iterator, so you usually wrap it in list().
Compare to a loop:
# Loop approach
squared = []
for x in numbers:
squared.append(x ** 2)
The map() version expresses the same idea more directly: "square each number."
Learn map and other transformations in my Functional Programming course.