0
list = [4, 7, 11, 15]

I'm trying to create a function to loop through list items, and find the difference between list[1] and list[0], and then list[2] and list[1], and then list[3] and list[2]... and so on for the entirety of the list. I am thinking of using a for loop but there might be a better way. Thanks.

output would be:

list_diff = [3, 4, 4]
def difference(list):
    for items in list():

or 

def difference(list):
    list_diff.append(list[1] - list[0])
    list_diff.append(list[2] - list[1])
etc.

...
meow11213
  • 11
  • 1

3 Answers3

3

If you are in Python 3.10+ you could try pairwise:

And you should try NOT to use the built-in list as the variable name.

It's quite easy and straightforward to make this one-line into a function.


from itertools import pairwise

>>>[b-a for a, b in pairwise(lst)]   # List Comprehension
[3, 4, 4]

# Or just zip()
diffs = [b-a for a, b in zip(lst, lst[1:]) ] # no import 

Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
0

You can simply loop for each item starting from element 1:

def diff(source):
  return [source[i] - source[i - 1] for i in range(1, len(source))]

print(diff([4, 7, 11, 15])) # [3, 4, 4]
Alex Rintt
  • 1,618
  • 1
  • 11
  • 18
0
num_list = [4, 7, 11, 15]

def difference(numbers):
    diff_list = []

    for i in range(1, len(numbers)):
        diff_list.append(numbers[i] - numbers[i - 1])

    return diff_list


print(difference(num_list))  # [3, 4, 4]
Leo
  • 369
  • 5