๐น 1. Importing reduce
from functools import reduce
reduce() is a function from the functools module.
It applies a function cumulatively to the items of a sequence.
It reduces the list to a single value.
๐น 2. Defining the List
data = [1, 2, 3]
A simple list with 3 elements.
reduce() will process these elements one by one.
๐น 3. Understanding the Lambda Function
lambda x, y: y - x
This is an anonymous function.
It takes two arguments:
x → accumulated value (previous result)
y → next element in the list
Important: It calculates y - x (not x - y) → this is the tricky part ⚠️
๐น 4. How reduce() Works Internally
reduce() applies the function like this:
๐ Step 1:
x = 1, y = 2
Compute: y - x = 2 - 1 = 1
๐ New result = 1
๐ Step 2:
x = 1 (previous result), y = 3
Compute: y - x = 3 - 1 = 2
๐ Final result = 2
๐น 5. Final Output
print(result)
✅ Output:
2

0 Comments:
Post a Comment