marcin_koss
marcin_koss

Reputation: 5882

Python: joining 2 lists of the same size

Let's say I have 2 following lists:

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

I want the result of join to be:

list3 [4,4,4,4]

What's would be the best way to do it?

Upvotes: 3

Views: 221

Answers (2)

actionshrimp
actionshrimp

Reputation: 5229

Extremely similar to Ignacio's answer, but for a tiny bit more brevity:

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 using Python 2.x you should replace zip with its iterator counterpart in itertools.izip for efficiency, but zip uses iterators by default in Python 3.

Upvotes: 10

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799450

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

or

list3 = map(operator.add, list1, list2)

Upvotes: 9

Related Questions