1

I have this code:

list_1 = [11, 22]
list_2 = [33, 44, 55 ,66]
list_3 = [77, 88 ,99]

I want to sum each elements in lists. i.e. 11 + 33 + 77, 11 + 33 + 88, … 22 + 33 + 77, 22 + 33 + 88… and put all the sums into a final list

I have these lines:

list_1 = [11, 22]
list_2 = [33, 44, 55 ,66]
list_3 = [77, 88 ,99]

result = []

for L_1 in list_1:
    for L_2 in list_2:
        for L_3 in list_3:
            result.append(L_1 + L_2 + L_3)

print result                   # to output all elements
print list(set(result))     # to not showing duplicates

The codes work well but looked clumsy. If there are 20 or more lists to take part in the calculation, it doesn’t looked good at all.

Could you please show me a better way?

halfer
  • 19,824
  • 17
  • 99
  • 186
Mark K
  • 8,767
  • 14
  • 58
  • 118

2 Answers2

3

This sort of combination is called the Cartesian product. You can get it using itertools.product.

from itertools import product

list_1 = [11, 22]
list_2 = [33, 44, 55, 66]
list_3 = [77, 88, 99]

result = {sum(t) for t in product(list_1, list_2, list_3)}
print(sorted(result))

output

[121, 132, 143, 154, 165, 176, 187]

You can even use product if you don't know in advance how many lists you have:

all_lists = list_1, list_2, list_3
result = {sum(t) for t in product(*all_lists)}

The product iterator yields tuples of the items from the iterables that you pass it. We then pass those tuples to the built-in sum function to perform the addition.

Here's what the "raw" output from product looks like:

from itertools import product

list_1 = [1, 2]
list_2 = [3, 4]
list_3 = [5, 6]

all_lists = list_1, list_2, list_3
for t in product(*all_lists):
    print(t)

output

(1, 3, 5)
(1, 3, 6)
(1, 4, 5)
(1, 4, 6)
(2, 3, 5)
(2, 3, 6)
(2, 4, 5)
(2, 4, 6)
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
1
map(sum, product(*lists))

Demo:

>>> from itertools import product
>>> lists = [11, 22], [33, 44, 55, 66], [77, 88, 99]
>>> map(sum, product(*lists))
[121, 132, 143, 132, 143, 154, 143, 154, 165, 154, 165, 176, 132, 143, 154, 143, 154, 165, 154, 165, 176, 165, 176, 187]
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107