Explanation:
🔹 Line 1: Creating a Nested List
data = [[1,2], [3,4], [5,6]]
Explanation
data is a list of lists (nested list).
It contains three separate sublists.
Each sublist holds two numbers.
We will later flatten these sublists into one single list.
🔹 Line 2: Creating an Empty Output List
flat = []
Explanation
flat is an empty list.
This list will store all numbers from the nested structure after flattening.
It starts empty and will be filled step by step.
🔹 Line 3: Flattening Using map() With Lambda
list(map(lambda x: flat.extend(x), data))
Explanation
This is the most important line. Here’s how it works:
A. map()
map() loops over each sublist inside data.
B. lambda x
x represents each sublist from data, one at a time:
First: [1, 2]
Second: [3, 4]
Third: [5, 6]
C. flat.extend(x)
.extend() adds each element of x into flat.
It does not add the sublist — it adds the individual numbers.
D. How flat changes
Step Value of x flat after extend
1 [1, 2] [1, 2]
2 [3, 4] [1, 2, 3, 4]
3 [5, 6] [1, 2, 3, 4, 5, 6]
E. Why list(...) ?
map() doesn’t run immediately.
Wrapping it with list() forces all iterations to execute.
🔹 Line 4: Printing the Final Output
print(flat)
Explanation
Prints the fully flattened list.
All nested values are now in one single list.
🎉 Final Output
[1, 2, 3, 4, 5, 6]


0 Comments:
Post a Comment