Junior — Middle
Can you explain what the built-in map function in Python does and how it is used?
sobes.tech AI
Answer from AI
The built-in map function in Python is used to apply a given function to each element of an iterable object (such as a list) sequentially and returns an iterator with the results.
Example of usage:
numbers = [1, 2, 3, 4]
# Function to square a number
def square(x):
return x * x
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # Outputs: [1, 4, 9, 16]
This is convenient for transforming data without explicit loops. It is also often used with lambda functions:
squared_numbers = map(lambda x: x*x, numbers)
map returns an iterator, so to get a list, you need to wrap the result in list().