-1

I have a list and want to know if the following can be done in Python without adding extra libraries to improve my code.

I want to get a list of the differences between elements of a list.

orig_list = [12, 27,31,55,95]

#desired output
spacings =[15, 4, 24,40]

I know I can do it by making a second list and subtracting it, I just wondered if there was another/better way.

Windy71
  • 851
  • 1
  • 9
  • 30
  • 1
    Does this answer your question? [Difference between consecutive elements in list](https://stackoverflow.com/questions/5314241/difference-between-consecutive-elements-in-list) – AMC Mar 17 '20 at 17:19
  • 1
    The more popular one is actually https://stackoverflow.com/questions/2400840/finding-differences-between-elements-of-a-list. – AMC Mar 17 '20 at 17:20
  • Hi AMC, the 'more popular one' would have answered my question, I must say I especially liked Drizzt's solution (below) although there is a similarly syntaxes answer on one of those you showed, much appreciated. – Windy71 Mar 18 '20 at 07:56

2 Answers2

2

You can use a list comprehension and zip:

[j-i for i,j in zip(orig_list[:-1], orig_list[1:])]
# [15, 4, 24, 40]

Though if NumPy is an option you have np.diff:

np.diff(orig_list)
# array([15,  4, 24, 40])
yatu
  • 86,083
  • 12
  • 84
  • 139
  • Hi yalu, I knew how to do it in numpy but couldn't think how I could do it in regular python, this works and saves importing a library for one operation, very much appreciated. – Windy71 Mar 17 '20 at 15:25
1

This is also possible with list comprehension, without using zip. Just iterate over the list elements from index 1 to n:

[orig_list[i]- orig_list[i-1] for i in range(1, len(orig_list))]

Drizzt
  • 133
  • 1
  • 2
  • 7