Code Explanation:
1. Importing Required Function
from functools import reduce
Explanation:
Imports the reduce() function from Python’s functools module.
reduce() is used to apply a function cumulatively to items in an iterable.
2. Creating a List of Lists
lists = [[1], [2, 3], [4]]
Explanation:
lists is a nested list (a list containing other lists).
Here:
First element → [1]
Second element → [2, 3]
Third element → [4]
3. Using reduce() to Flatten the List
result = reduce(lambda a, b: a + b, lists)
3.1 reduce()
reduce(function, iterable) repeatedly applies function to elements of iterable.
3.2 lambda a, b: a + b
This is an anonymous function.
It takes two lists (a and b) and returns their concatenation (a + b).
3.3 Step-by-step working
Step a b a + b
1 [1] [2, 3] [1, 2, 3]
2 [1, 2, 3] [4] [1, 2, 3, 4]
So the final value of result becomes:
[1, 2, 3, 4]
4. Printing the Output
print("Flattened:", result)
Explanation:
Prints the text "Flattened:" followed by the flattened list stored in result.
5. Final Output
Flattened: [1, 2, 3, 4]


0 Comments:
Post a Comment