Explanation:
๐น Create the First List
a = [1, 2, 3]
A list named a is created containing three elements.
Current value:
a = [1, 2, 3]
๐น Create the Second List
b = [4, 5]
Another list named b is created.
Current value:
b = [4, 5]
Notice:
List a has 3 elements
List b has 2 elements
๐น Call map()
map(lambda x, y: x + y, a, b)
The map() function applies the given function to elements from both lists one by one.
The lambda function is:
lambda x, y: x + y
Meaning:
Take one element from a and one element from b, then return their sum.
๐น First Iteration
Python picks:
x = 1
y = 4
Calculation:
1 + 4
Result:
5
Current mapped values:
[5]
๐น Second Iteration
Python picks:
x = 2
y = 5
Calculation:
2 + 5
Result:
7
Current mapped values:
[5, 7]
๐น What About 3?
Now Python tries to continue.
Remaining elements:
a → [3]
b → []
The second list has no more elements.
Since map() stops when the shortest iterable is exhausted, it does not process:
3
So:
3 + ?
never happens.
๐น Visual Representation
List A List B
1 ───────► 4 = 5
2 ───────► 5 = 7
3 ───────► ❌ No element
↓
Stop
๐นConvert Map Object into a List
list(map(...))
map() returns a map object (iterator).
It is converted into a list.
Current result:
[5, 7]
๐น Print the Result
print([5, 7])
Output:
[5, 7]
⚡ Execution Flow
Initial lists:
a = [1,2,3]
b = [4,5]
↓
First pair:
1 + 4 = 5
↓
Second pair:
2 + 5 = 7
↓
Third pair:
3 + ❌
Second list ends.
↓
map() stops.
↓
Final result:
[5, 7]
๐ Iteration Table
Iteration x y Result
1 1 4 5
2 2 5 7
3 3 ❌ No value Stops
❌ Common Mistake
Many developers expect:
[5, 7, 3]
or
[5, 7, Error]
❌ Incorrect.
map() does not pad missing values or raise an error.
It simply stops as soon as the shortest iterable is exhausted.
๐ก Similar Example
print(list(map(lambda x, y: x * y, [1,2,3], [10])))
Output:
[10]
Only the first pair is processed because the second list contains only one element.
๐ฏ Final Result
[5, 7]
✅ Correct Output
[5, 7]

0 Comments:
Post a Comment