Junior — Middle
What is the map function in Python used for and how is it applied?
sobes.tech AI
Answer from AI
The map function in Python is designed to apply a given function to each element of an iterable object (such as a list) and returns an iterator with the results. It is a convenient way to transform all elements of a collection without using explicit loops.
Example usage:
numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # Outputs: [1, 4, 9, 16]
Here, map applies a lambda function that squares a number to all elements of the list numbers.