Error when lambda expression takes two arguments in Python
I am new to Python and have practiced the basics. I am using a lambda expression to take two arguments and perform quadratic operations on them (ex:) var ** 2
. Two arguments come from zip(list1, list2)
. For this I get TypeError
. I tried to find a solution but didn't get it. I even tried to write lambda arguments in parentheses (ex:) lambda (v1,v2):
, but that gave up SyntaxError
.
Below is the python code:
list1 = [1,2,3,4] list2 = [5,6,7,8] print ( list(map(lambda v1,v2: (v1**2, v2**2), list(zip(list1, list2)))) )
Mistake:
TypeError Traceback (most recent call last)
<ipython-input-241-e93d37efc752> in <module>()
1 list1 = [1,2,3,4]
2 list2 = [5,6,7,8]
----> 3 print ( list(map(lambda v1,v2: (v1**2, v2**2), list(zip(list1, list2)))) )
TypeError: <lambda>() missing 1 required positional argument: 'v2'
source to share
You are specifying one list as an argument map
, so it map
calls yours lambda
with one list item at a time - that's one argument, even though it's a tuple. You probably want:
print ( list(map(lambda v: (v[0]**2, v[1]**2), zip(list1, list2))) )
so that your element from the list is passed as the only argument lambda
. If you insist on two arguments lambda
, drop zip
and pass your lists directly to map
as separate arguments:
print ( list(map(lambda v1,v2: (v1**2, v2**2), list1, list2)) )
source to share
Your print map
will call the lambda function on a list of tuples (as list(zip(list1, list2))
output a list of tuples).
So, for example, you can do:
print(list(map(lambda(v1,v2): (v1**2, v2**2), list(zip(list1, list2)))))
Your lambda function will use the tuple (v1, v2) as parameters instead of two parameters.
source to share