when I use lambda as a function,the result is list connection. but when I use lambda with map,the result is the sum of two lists.

res = [[1]]
g = lambda x, y: x + y
print(g(res[-1] + [0], [0] + res[-1]))
print(list(map(lambda x, y: x + y, res[-1] + [0], [0] + res[-1])))

[1, 0, 0, 1] [1, 1]

1 Answers


This line is straightforward:

print(g(res[-1] + [0], [0] + res[-1]))

It calls the function just once with arguments [1, 0] and [0, 1]. These two list concatenated produce [1,0,0,1]


My first answer was describing the case with one iterable, but this is a map with two iterables.

The line with map calls the function (lambda or regular, does not matter) one time for each set of arguments. How exactly are these arguments formed is described in the docs:

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.

I have reformatted that line:

    lambda x, y: x + y,  # call this function repeatedly
    res[-1] + [0],       # X's are takes from this list,
    [0] + res[-1]        # Y's are taken from this list,

There will be as many calls as there are values in the lists (in the shortest one, to be exact). First call has arguments 1, 0; second call's arguments are 0, 1. Each set of arguments has two values, because there are two lists passed (lists are iterables, of course) so it matches the function which expects two arguments (x and y). If there were three or more iterables, a TypeError would occur.

First call adds 1+0, second call adds 0+1. The resulting list is [1,1].

AnOther example (100+1, 200+2, 300+3) -> [101,202,303]:

    lambda x, y: x + y,  # call this function repeatedly
    [100,200,300],       # X's are takes from this list,
    [1,2,3]              # Y's are taken from this list,

You may add debugging output to the definition of g to see what is being computed.

def g(x, y): 
    print(f"debug: {x} + {y} -> {x+y}")
    return x+y 

It makes no difference if the function is defined as lambda or not. You can write the map like this:

print(list(map(g, res[-1] + [0], [0] + res[-1])))

and test the program with different data.