There are two lists of the same length. How to get a third list with elements are equal to the sum of the corresponding elements of the two original lists?
For example:
l1 = [1, 2, 10, 7]
l2 = [0, 6, 1, 2]
l = [1, 8, 11, 9]
There are two lists of the same length. How to get a third list with elements are equal to the sum of the corresponding elements of the two original lists?
For example:
l1 = [1, 2, 10, 7]
l2 = [0, 6, 1, 2]
l = [1, 8, 11, 9]
In case you have to do some operations for elements with same indexes with two (or more) lists of the same size, it is a good idea to use zip()
function.
This function takes two equal-length collections, and merges them together in pairs.
You can find out some fundamental information in Python docs
To solve your problem you should try:
l = [x+y for x,y in zip(l1,l2)]
With itertools.izip, it's something like this:
import itertools
[i + j for i, j in itertools.izip(l1, l2)]
You can think ofitertools.izip(l1, l2)
as something like a sequence that consists of pairs of members from the two original sequences.