maynull
maynull

Reputation: 2046

How can I rewrite this code using map and lambda functions?

I'm trying to convert this list comprehension code to map and lambda code.

>>>list1 = [1,2,3]
>>>list2 = [10,20,30]
>>>print([m+n for m,n in zip(list1, list2)])
[11, 22, 33]

The code below is what I tried, but it shows TypeError

>>>print(list(map(lambda m,n:m+n, zip(list1, list2))))
Traceback (most recent call last):
  File "<console>", line 1, in <module>   
TypeError: <lambda>() missing 1 required positional argument: 'n'

I read that list comprehensions and labda function are interconvertible. Please point out my mistake!

Upvotes: 0

Views: 183

Answers (1)

niemmi
niemmi

Reputation: 17263

lambda gets only one argument which is a tuple from zip that you need to unpack yourself:

>>> list1 = [1,2,3]
>>> list2 = [10,20,30]
>>> list(map(lambda x: x[0]+x[1], zip(list1, list2)))
[11, 22, 33]

Upvotes: 2

Related Questions