Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading