Can I insert a tuple (or a list) of arguments into a function using map?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 Can I Insert A Tuple (Or A List) Of Arguments Into A Function Using Map?
01:13 Accepted Answer Score 5
01:54 Answer 2 Score 3
02:17 Answer 3 Score 5
02:47 Answer 4 Score 1
03:01 Thank you
--
Full question
https://stackoverflow.com/questions/6204...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #function #lambda
#avk47
ACCEPTED ANSWER
Score 5
the lambda function can't unpack the arguments automatically. map passes the tuple to the function, not 3 arguments. You have to take one argument as a tuple and access the elements:
test_values = [(2, 1, 4), (5, 2, 7), (3, 1, 10), (3, 4, 5)]
print(list(map(lambda t: t[1] <= t[0] <= t[2], test_values)))
that's why a simple list comprehension is much better: you can unpack the tuple in the loop:
[low <= num <= high for num,low,high in test_values]
it's also faster as you don't have to chain function calls, and less cryptic. map + lambda combination isn't the best in speed and readability.
result is [True, True, True, False] for both.
ANSWER 2
Score 5
You are seeing the difference between taking a tuple as an argument, and taking the elements of a tuple as separate arguments. You could write
print(list(map(lambda t: t[1] <= t[0] <= t[2], test_values)))
or you can use itertools.starmap, which effectively unpacks the tuple for you.
from itertools import startup
print(list(starmap(lambda num, low, high: low <= num <= high, test_values)))
In Python, though, it is usually clearer to use a list comprehension to build a list than explicit use of map and a function:
print([low <= num <= high for num, low, high in test_values])
ANSWER 3
Score 3
You can use zip and tuple unpacking:
test_values = [(2, 1, 4), (5, 2, 7), (3, 1, 10), (3, 4, 5)]
print(list(map(lambda num, low, high: low <= num <= high, *zip(*test_values))))
Returns
[True, True, True, False]
I would add that a list comprehension is vastly more readable for this kind of thing. Even Guido hates map...
ANSWER 4
Score 1
I would do this just with 1-line for loop like this:
print([range_check(*x) for x in test_values])
This * in front of x in function argument makes your tuple to unpack into more variables.