How to find differences between elements of a list with Python?

Estimated read time 1 min read

To find differences between elements of a list in Python, you can iterate over the list and compare adjacent elements. Here’s an example:

def find_differences(lst):
    differences = []
    for i in range(len(lst) - 1):
        diff = lst[i+1] - lst[i]
        differences.append(diff)
    return differences

# Example usage
numbers = [10, 15, 22, 31, 45]
result = find_differences(numbers)
print(result)  # Output: [5, 7, 9, 14]

In the above code, the find_differences function takes a list as input and initializes an empty list differences to store the differences between adjacent elements. It iterates over the list using a for loop, starting from the first element (lst[i]) and comparing it with the next element (lst[i+1]). The difference between the elements is calculated by subtracting the current element from the next element. The differences are then appended to the differences list. Finally, the function returns the differences list.

In the example usage, we create a list of numbers and call the find_differences function with that list. The result is then printed, showing the differences between adjacent elements in the original list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply