# map, lambda confusion

What am I doing wrong here? The map creates an iterator OK, but when I try to list it I get a type error.

list(map(lambda x,y : x + y,[(1,2),(3,4),(5,6)]))

TypeError                                 Traceback (most recent call last)
<ipython-input-11-031490d94268> in <module>()
----> 1 list(map(lambda x,y : x + y,[(Integer(1),Integer(2)),(Integer(3),Integer(4)),(Integer(5),Integer(6))]))

TypeError: <lambda>() missing 1 required positional argument: 'y'

edit retag close merge delete

Sort by ยป oldest newest most voted

The error message indicates an error with the lambda function.

That lambda function takes two arguments x and y.

The error message complains that it only received x and not y.

Indeed, the lambda function expects two arguments x and y but receives a single argument which is a tuple (a, b).

The tuple is not automatically unpacked to give x = a and y = b.

Instead, what happens is x = (a, b) and there is no y, so lambda complains.

Illustration:

sage: f = lambda x, y: x + y
sage: ell = [(1, 2), (3, 4), (5, 6)]

sage: list(map(f, ell))
Traceback (most recent call last)
...
TypeError: <lambda>() missing 1 required positional argument: 'y'


Compare:

sage: f(1, 2)
3

sage: f((1, 2))
Traceback (most recent call last)
...
TypeError: <lambda>() missing 1 required positional argument: 'y'


Use sum, which takes an iterable as argument, instead of the custom f:

sage: list(map(sum, ell))
[3, 7, 11]


Or drop map and use list comprehension.

Either directly:

sage: [x + y for x, y in ell]
[3, 7, 11]


Or using f and * for tuple unpacking:

sage: [f(*t) for t in ell]
[3, 7, 11]

more

Please start posting anonymously - your entry will be published after you log in or create a new account.

## Stats

Asked: 2020-09-13 04:17:44 +0200

Seen: 72 times

Last updated: Sep 13 '20