Get the difference between consecutive numbers in a list

avatar

Borislav Hadzhiev

Last updated: Jul 9, 2022

banner

Photo from Unsplash

Get the difference between consecutive numbers in a list #

To get the difference between consecutive numbers in a list:

  1. Use the enumerate() function to get an object containing index, item tuples.
  2. Use a list comprehension to iterate over the object.
  3. Starting with the second item, subtract each item from the previous.
main.py
my_list = [1, 3, 7, 14] result = [ item - my_list[idx - 1] for idx, item in enumerate(my_list) ][1:] print(result) # 👉️ [2, 4, 7]

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index, and the second - the item.

main.py
my_list = [1, 3, 7, 14] # 👇️ [(0, 1), (1, 3), (2, 7), (3, 14)] print(list(enumerate(my_list)))

The first item in each tuple is the index, and the second is the list item at the given index.

We used a list comprehension to iterate over the enumerate object.

main.py
my_list = [1, 3, 7, 14] result = [ item - my_list[idx - 1] for idx, item in enumerate(my_list) ][1:] print(result) # 👉️ [2, 4, 7]
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we subtract the current item from the previous item in the list and return the result.

An important thing to note is - we used list slicing [1:] to omit the first item from the result.

This is needed because we don't want to subtract list item at index -1 from list item at index 0.

The syntax for list slicing is my_list[start:stop:step] where the start value is inclusive, and the stop value is exclusive.

If the stop value is omitted, the slice goes to the end of the list.

Alternatively, you can check if the value of the index is greater than 0.

main.py
my_list = [1, 3, 7, 14] result = [ item - my_list[idx - 1] for idx, item in enumerate(my_list) if idx > 0 ] print(result) # 👉️ [2, 4, 7]

If the index is greater than 0, we know that we aren't in the first iteration and can safely subtract item 0 from item 1, etc.

Which approach you pick is a matter of personal preference. I'd go with list slicing since I find it more intuitive than checking for a condition we only care about on the first iteration.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.