Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python map function with min argument and two lists

Tags:

python

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.

like image 470
jack.b Avatar asked Aug 02 '16 05:08

jack.b


4 Answers

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

like image 109
John La Rooy Avatar answered Nov 02 '22 23:11

John La Rooy


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.

like image 34
user94559 Avatar answered Nov 02 '22 23:11

user94559


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]

like image 20
Vaibhav Bajaj Avatar answered Nov 03 '22 00:11

Vaibhav Bajaj


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.

like image 30
nalzok Avatar answered Nov 03 '22 00:11

nalzok