-2

I have this array:

array = [1 1 2 3 5 8]

How do I get the difference between adjacent items so that I'll obtain this array:

diff = [0 1 1 2 3]

So far, this has been my attempt but I know why this doesn't work bc i and h are not really integers

array = []
diff = []


for i in array:
         h = i - 1     # h is not int() here coz it's not an index
         if h >= 0:
              j = i.get() - h.get()
              diff.append(j)
         else:
              pass

I'm newbie in programming, thoughts you'll share will be appreciated

MSDS
  • 5
  • 2

3 Answers3

2

You can use zip function.

>>> array = [1, 1, 2, 3, 5, 8]
>>> [j - i for i, j in zip(array, array[1:])]
[0, 1, 1, 2, 3]
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
0

The most straight forward way is to either use the index directly with range or use enumerate to get both the index and the current value. With range:

a = [1, 1, 2, 3, 5, 8]
b = []

for i in range(1, len(a)):  # i = 1 -> length of a
  b.append(a[i] - a[i-1])  # add the difference between this element and the element before it to `b`

>>> b
[0, 1, 1, 2, 3]
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
-1
diff = [array[i + 1] - array[i] for i in range(len(array) - 1)]
11_22_33
  • 116
  • 1
  • 15