Code Explanation:
1. Import reduce from functools
from functools import reduce
reduce is a function that applies a given operation cumulatively to all elements in a list.
Example: reduce(lambda x, y: x * y, [2, 3, 4]) → ((2*3)*4) = 24.
2. Define a list of numbers
nums = [2, 3, 4, 5]
A simple list of integers.
Contents: [2, 3, 4, 5].
3. Calculate the product using reduce
product = reduce(lambda x, y: x * y, nums)
The lambda multiplies elements pair by pair.
Step-by-step:
(2 * 3) = 6
(6 * 4) = 24
(24 * 5) = 120
So, product = 120.
4. Remove an element from the list
nums.remove(3)
Removes the first occurrence of 3 from the list.
Now nums = [2, 4, 5].
5. Use reduce to calculate sum with initial value
s = reduce(lambda x, y: x + y, nums, 10)
Here 10 is the initial value.
Process:
Start = 10
(10 + 2) = 12
(12 + 4) = 16
(16 + 5) = 21
So, s = 21.
6. Print results
print(product, s)
Prints both values:
Output →
120 21
.png)

0 Comments:
Post a Comment