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

Making a loop to calculate [n] – [n+1] inside a single python list

I’m trying to calculate, with a loop, a substraction between n element and n+1 element inside a single python list.

For exemple :

list = [26.5, 17.3, 5.9, 10.34, 3.87]

    # expected calculation
    # 26.5 - 17.3 = 9.2
    # 17.3 - 5.9 = 11.4
    # ...

    # expected result
    # list_2 = [9.2, 11.4, -4.44, 6.47]

I tried with :

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

list_2 = [n-(n+1) for n in list]
    # output
    # [-1.0, -1.0, -1.0, -1.0, -1.0]

-----------------------------------------
list_2 = []
for n in list:
    list_2 += list[n] - list[n+1]
    # output
    # TypeError: list indices must be integers or slices, not float
    
    # with correction of 'TypeError'
    list_2 += list[int(n)] - list[int(n+1)]
    # output
    # TypeError: 'float' object is not iterable

The problem look simple but… I can’t do it.
Do you have an idea?
If it is possible, I’m looking for a native python3 solution.

Thank you per advance and have a nice day/evening.

>Solution :

Try this.

l = [26.5, 17.3, 5.9, 10.34, 3.87]

result = [l[i] - l[i + 1] for i in range(len(l) - 1)]
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