Explanation:
1. Defining the Function
def square(n):
return n ** 2
A function named square is defined. It takes one argument, n.
The function returns the square of n (i.e., n ** 2).
2. Using map()
result = map(square, [1, 2, 3])
The map() function applies a given function (here, square) to each item in an iterable (here, the list [1, 2, 3]).
The square function is called for each element in the list:
For 1: square(1) → 1 ** 2 → 1
For 2: square(2) → 2 ** 2 → 4
For 3: square(3) → 3 ** 2 → 9
The map() function returns a map object, which is an iterator that contains the results (1, 4, 9).
3. Converting to a List
print(list(result))
The map object is converted into a list using list(result), which materializes the results of the map() operation.
Final Output:
[1, 4, 9]
0 Comments:
Post a Comment