I'm trying to map a function that takes 2 arguments to a list:
my_func = lambda index, value: value.upper() if index % 2 else value.lower()
import string
alphabet = string.ascii_lowercase
n = map(my_func, enumerate(alphabet))
for element in n:
print(element)
This gives me a TypeError: <lambda>() missing 1 required positional argument: 'value'
.
What is the correct way to map my lambda onto this input?
map
will pass each value fromenumerate
as a single parameter to the callback, i.e. thelambda
will be called with a tuple as argument. It would be pretty surprising behaviour ifmap
would unpack arguments which look unpackable, since then its behaviour would depend on the values it iterates over.To expand iterable arguments, use
starmap
instead, which "applies a*
(star)" when passing arguments:Python can't unpack
lambda
parameters automatically.But you can get round this by passing an extra
range
argument tomap
:As per the docs:
Python cannot unpack lambda parameters automatically.
enumerate
returns atuple
, solambda
has to take that tuple as sole argumentYou need:
Considering now the ugliness of
map
+lambda
+ manual unpacking, I'd advise the alternate generator comprehension instead:(I removed the
lower()
call since your input is already lowercase)