Im having trouble figuring out why this map function is producing the output it's producing. The code is as follows:
L1 = [1, 28, 36]
L2 = [2, 57, 9]
print map(min, L1, L2)
output is: [1, 28, 9]
I understand it took the min values from the first list, but why did it not take the 2 from the second, and instead took the 9. Appreciate any feedback, thank you.
The result is made up from
[min(L1[0], L2[0]), min(L1[1], L2[1]), min(L1[2], L2[2])]
so min
is being called on each pair of values to construct the new list
map(min, L1, L2)
means roughly this:
[min(L1[0], L2[0]), min(L1[1], L2[1]), min(L1[2], L2[2])]
So the min of [1,2] (first element of each list) is 1, min of [28,57] is 28, and min of [36,9] is 9.
You probably wanted map(min, [L1, L2])
instead.
The statement:
map(min, L1, L2)
compares each elements of the two lists with the same index.
Thus,
It performs:
list = []
list.append(min(1,2)) #1
list.append(min(28,57)) #28
list.append(min(36,9)) #9
print list
leading to the output [1, 28, 9]
Let's take a look at the document:
map(function, iterable, ...)
Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. ...
Here, in parallel means items of same index from different iterable
are passed to function
for each index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With