0

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]
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487

2 Answers2

1

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)]
tema
  • 1,089
  • 13
  • 31
  • 1
    Some explanation might be nice--a description of what `zip` means, or at least a link to the docs, and maybe a link to list comprehensions in the tutorial in case he's never seen one. – abarnert Apr 30 '15 at 22:31
1

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.

Ami Tavory
  • 71,268
  • 10
  • 134
  • 170