How to calculate difference between adjacent elements in a list with Python

2 Answers

0 votes
# Adjacent = two numbers that are next to each other in a list
 
lst = [3, 8, 0, 4, 7, 2, 9, 1]
 
diff_list = []
for x, y in zip(lst[0::], lst[1::]):
    diff_list.append(y - x)
      
print(str(diff_list))
 
 
  
 
   
'''
run:
   
[5, -8, 4, 3, -5, 7, -8]
   
'''

 



answered Feb 1, 2024 by avibootz
edited Feb 1, 2024 by avibootz
0 votes
# Adjacent = two numbers that are next to each other in a list

import numpy as np

lst = [3, 8, 0, 4, 7, 2, 9, 1]

diff_list = np.diff(lst)
     
print(str(diff_list))



  
'''
run:
  
[ 5 -8  4  3 -5  7 -8]
  
'''

 



answered Feb 1, 2024 by avibootz
...