How to get the summation of each of the 2 elements?

Question:

For example the list is:

stuff = [1, 2, 5, 7]

Now I created a new list named sum_list to store the summation of each of the 2 elements in stuff. The element in the sum_list will be 1+2, 1+5, 1+7, 2+5, 2+7, 5+7:

[3, 6, 8, 7, 9, 12]
Asked By: William

||

Answers:

Use itertools.combinations to get all the combinations of 2 elements, and sum to sum them:

>>> stuff = [1, 2, 5, 7]
>>> from itertools import combinations
>>> [sum(c) for c in combinations(stuff, 2)]
[3, 6, 8, 7, 9, 12]
Answered By: Samwise

You can do this in one hideous list comprehension:

[a + b for i, a in enumerate(my_list, start=1) for b in my_list[i:]]

Nested loops may be clearer:

result = []
for i, a in enumerate(my_list, start=1):
    for b in my_list[i:]:
        result.append(a + b)
Answered By: Jack Deeth
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.