0

I want to get the difference of list 2nd element and 1st element

I tried iterating the list using I with range but getting an index out of bound also not getting proper results

l=[0,6,12,18,24,30]
for i in range(l[0],l[-1]):
    #print(l[0])
   # print(l[i+1]-l[i])
    n=l[i]
    print("N->",n)
    m=l[i+1]
    print("M->",m)

    p=m-n
    print(p)

For example

L = [2, 4, 32, 314, 544]

Output:

2
28
282
230
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Saad Ghojaria
  • 41
  • 1
  • 8

2 Answers2

1
[l[i] - l[i - 1] for i in range(1, len(l))]
fendall
  • 524
  • 2
  • 8
1

You can avoid the error by checking if i+1 >= len(l)

Code:

l=[2, 4, 32, 314, 544]
for i in range(0,len(l)):
  if i+1 >= len(l):
    break
  n=l[i]
  print("N->",n)
  m=l[i+1]
  print("M->",m)
  p=m-n
  print(p)
Yash
  • 3,438
  • 2
  • 17
  • 33