Code Explanation:
1) from functools import reduce
Imports the reduce function from Python’s functools module.
reduce(func, iterable[, initializer]) applies func cumulatively to elements of iterable, reducing it to a single value.
2) nums = [2, 3, 4]
A list nums is created with three integers: [2, 3, 4].
3) product = reduce(lambda x, y: x * y, nums)
Applies the multiplication lambda (x * y) across the list [2, 3, 4].
Step-by-step:
First call: x=2, y=3 → 6
Second call: x=6, y=4 → 24
Final result stored in product is:
24
4) nums.append(5)
Appends 5 to the list.
Now nums = [2, 3, 4, 5].
5) total = reduce(lambda x, y: x + y, nums, 10)
This time we use addition lambda (x + y) with an initializer 10.
Steps:
Start with initial value 10.
10 + 2 = 12
12 + 3 = 15
15 + 4 = 19
19 + 5 = 24
Final result stored in total is:
24
6) print(product, total)
Prints both computed values:
product = 24
total = 24
Final Output
24 24
.png)

0 Comments:
Post a Comment