I am new to Python and practicing basics. I am using a lambda expression to take two arguments and performing square operations on them (eg: var ** 2). The two arguments are coming from the zip(list1, list2). I am getting TypeError for this. I tried searching for the solution but didn't get any. I even tried writing lambda arguments in parenthesis (eg: lambda (v1,v2):) but that threw 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)))) )
Error:
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'
You're giving a single list as argument to map, thus map calls your lambda with one element of the list at a time - that is one argument, even though it is a tuple. What you probably want is:
print ( list(map(lambda v: (v[0]**2, v[1]**2), zip(list1, list2))) )
so that your item from the list is passed as a sole argument to lambda.
If you insist on the two-argument lambda, discard zip and pass your lists directly to map as separate arguments:
print ( list(map(lambda v1,v2: (v1**2, v2**2), list1, list2)) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With