Python: merging two lists of the same size

Let's say I have 2 of the following lists:

list1 = [1,1,1,1] list2 = [3,3,3,3]

I want the result of the union to be:

list3 [4,4,4,4]

What would be the best way to do this?

+3
source share
2 answers

Very similar to Ignacio's answer, but for a tiny cue ball:

list3 = [sum(i) for i in zip(list1, list2)]

or

list3 = map(sum, zip(list1, list2))

I prefer the map version myself.

Edit: As JBernardo rightly points out, if you are using Python 2.x, you should replace zip with your iterator in itertools.izip for efficiency, but zip uses the default iterators in Python 3.

+11
source
list3 = [x + y for (x, y) in itertools.izip(list1, list2)]

or

list3 = map(operator.add, list1, list2)
+9
source

All Articles