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]
CodePudding user response:
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)
CodePudding user response:
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]