Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python syntax for a map(max()) call

I came across this particular piece of code in one of "beginner" tutorials for Python. It doesn't make logical sense, if someone can explain it to me I'd appreciate it.

print(list(map(max, [4,3,7], [1,9,2])))

I thought it would print [4,9] (by running max() on each of the provided lists and then printing max value in each list). Instead it prints [4,9,7]. Why three numbers?

like image 232
LNI Avatar asked Jan 04 '23 16:01

LNI


1 Answers

You're thinking of

print(list(map(max, [[4,3,7], [1,9,2]])))
#                   ^                ^

providing one sequence to map, whose elements are [4,3,7] and [1,9,2].

The code you've posted:

print(list(map(max, [4,3,7], [1,9,2])))

provides [4,3,7] and [1,9,2] as separate arguments to map. When map receives multiple sequences, it iterates over those sequences in parallel and passes corresponding elements as separate arguments to the mapped function, which is max.

Instead of calling

max([4, 3, 7])
max([1, 9, 2])

it calls

max(4, 1)
max(3, 9)
max(7, 2)
like image 91
user2357112 supports Monica Avatar answered Jan 18 '23 17:01

user2357112 supports Monica