Code Explanation:
Line 1: Importing reduce
from functools import reduce
This imports the reduce() function from the functools module.
reduce() repeatedly applies a function to elements of a list, reducing the list to a single result.
Line 2: Creating the list
lst = [1, 2, 3, 4]
This defines a list lst with integers: [1, 2, 3, 4].
You will process this list using reduce() to get the squares of even numbers only.
Line 3–7: Using reduce() to build the result
res = reduce(
lambda acc, x: acc + [x**2] if x % 2 == 0 else acc,
lst, []
)
Explanation of reduce(function, iterable, initializer):
Function:
lambda acc, x: acc + [x**2] if x % 2 == 0 else acc
acc is the accumulator (starts as an empty list []).
x is the current element from the list.
If x is even (x % 2 == 0), add its square (x**2) to the accumulator.
If x is odd, return the accumulator unchanged.
Iterable: lst = [1, 2, 3, 4]
Initializer: []
Start with an empty list.
Line 8: Print the result
print(res)
[4, 16]
Final Result:
This code returns a list of squares of even numbers from the input list [1, 2, 3, 4].
Even numbers: 2, 4
Their squares: 4, 16
Output: [4, 16]
Final Output:
[4,16]
.png)

0 Comments:
Post a Comment