in Code

Python in Functional Style: How to add 2 lists of integers without using loops

Usually you’d add a list of integers this way:

a = [2, 2, 2, 2]
b = [2, 2, 2, 2]
c = []
for i in range(len(a)):
 c.append(a[i] + b[i])

You can do it functionally without any loops in different ways:



Using map and a lambda that adds them up

c = list(map(lambda x,y: x+y, a, b))

or you can import the add operator as a named function

from operator import add
c = list(map(add, a, b))


Ever zipped two lists into a list of tuples?

There’s another more convoluted way if you want to play with “zip”.

Close End 10cm 80cm 5# 10pcs white Metal Zipper for Sewing ...
Imagine a jacket zipper and the teeth on each side of the zipper is one element on each one of the list.


When you zip the lists a and b, you end up with a list of tuples of matching elements from the given lists.

>>> list(zip(a,b))
[(2, 2), (2, 2), (2, 2), (2, 2)]

you could now map a function to add the elements within each tuple on that list.


>>> list(map(lambda tup: tup[0]+tup[1], zip(a,b)))
[4, 4, 4, 4]


Notice how we don’t convert to list after zip, we can work directly with the zip iterator, we only convert to list with the final map iterator.

Python 2 & 3 Note:

In Python 2 it’s not necessary to use list(), the map() and zip() methods return lists there. But stay away from Python 2, a lot of projects are now discontinuing support.

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.