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:

[pastacode lang=”python” manual=”a%20%3D%20%5B2%2C%202%2C%202%2C%202%5D%0Ab%20%3D%20%5B2%2C%202%2C%202%2C%202%5D%0Ac%20%3D%20%5B%5D%0Afor%20i%20in%20range(len(a))%3A%0A%20c.append(a%5Bi%5D%20%2B%20b%5Bi%5D)” message=”” highlight=”” provider=”manual”/]

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



Using map and a lambda that adds them up

[pastacode lang=”python” manual=”c%20%3D%20list(map(lambda%20x%2Cy%3A%20x%2By%2C%20a%2C%20b))” message=”” highlight=”” provider=”manual”/]

or you can import the add operator as a named function

[pastacode lang=”python” manual=”from%20operator%20import%20add%0Ac%20%3D%20list(map(add%2C%20a%2C%20b))” message=”” highlight=”” provider=”manual”/]


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.

[pastacode lang=”python” manual=”%3E%3E%3E%20list(zip(a%2Cb))%0A%5B(2%2C%202)%2C%20(2%2C%202)%2C%20(2%2C%202)%2C%20(2%2C%202)%5D” message=”” highlight=”” provider=”manual”/]

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


[pastacode lang=”python” manual=”%3E%3E%3E%20list(map(lambda%20tup%3A%20tup%5B0%5D%2Btup%5B1%5D%2C%20zip(a%2Cb)))%0A%5B4%2C%204%2C%204%2C%204%5D” message=”” highlight=”” provider=”manual”/]


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.