Code Explanation:
Importing the reduce function
from functools import reduce
reduce() is not a built-in function in Python 3, so you must import it from the functools module.
It reduces a sequence to a single value by applying a function cumulatively.
Defining the list
data = [1, 2, 3, 4, 5]
A list named data is created, containing integers from 1 to 5.
This is the input sequence we’ll use with reduce().
Applying reduce() to sum even numbers
result = reduce(
lambda acc, x: acc + x if x % 2 == 0 else acc,
data,
0
)
Explanation of parts:
lambda acc, x: acc + x if x % 2 == 0 else acc
This is a lambda (anonymous) function used by reduce().
acc: Accumulator (the running total).
x: Current item from the list.
Condition: If x is even (x % 2 == 0), then add x to acc.
Otherwise, keep acc the same.
data
The iterable passed to reduce() — the list [1, 2, 3, 4, 5].
0
The initial value of acc. We start summing from 0.
Line 8: Printing the result
print(result)
Prints the final accumulated result:
6
Final Output:
6
.png)

0 Comments:
Post a Comment