1
votes

I want to know how can I make a python function that does the same as mapcar of lisp.

From the mapcar lisp documentation :

mapcar operates on successive elements of the lists. function is applied to the first element of each list, then to the second element of each list, and so on. The iteration terminates when the shortest list runs out, and excess elements in other lists are ignored. The value returned by mapcar is a list of the results of successive calls to function.

For example,

list1 = [1, 2, 3, 4, 5]
list2 = [5, 4, 3, 2, 1]

def sum(firstNumber, secondNumber):
    return firstNumber + secondNumber

sumOfLists = mapcar(sum, list1, list2)

print(sumOfLists)
# [6, 6, 6, 6, 6]
2

2 Answers

3
votes

Use map, and also there is an operator for adding operator.add:

>>> import operator
>>> list(map(operator.add, list1, list2))
[6, 6, 6, 6, 6]

From the documentation. map takes a function as first argument, and a variable number of iterable arguments. The key is that the function should take as many arguments as iterables are given to map. That is the only "restriction" to take into account. So, for example:

map(lambda x: x+1,         range(10))
map(lambda x, y: x+y,      range(10), range(10))
map(lambda x, y, z: x+y+z, range(10), range(10), range(10))

And so on...

Also it can take any other function defined by the user:

def checkString(s):
    return isinstance(s, str) and len(s) > 10

>>> list(map(checkString, ["foo", "fooooooooooooooooooooo"]))
[False, True]
1
votes

This can be achieved in this way: sumOfLists = map(sum, zip(list1, list2)) You also do not need to define the sum function, as it is built-in.