w3resource

Python: Find the difference between consecutive numbers in a given list


Difference Between Consecutive Numbers

Write a Python program to find the difference between consecutive numbers in a given list.

Visual Presentation:

Python List: Find the difference between consecutive numbers in a given list.

Sample Solution:

Python Code:

# Define a function 'diff_consecutive_nums' that calculates the differences between consecutive numbers in a list
def diff_consecutive_nums(nums):
    # Use a list comprehension and the 'zip' function to calculate differences between consecutive numbers
    result = [b - a for a, b in zip(nums[:-1], nums[1:])]
    return result

# Create a list 'nums1' containing numbers
nums1 = [1, 1, 3, 4, 4, 5, 6, 7]

# Print a message indicating the original list
print("Original list:")
# Print the contents of 'nums1'
print(nums1)

# Print a message indicating that the differences between consecutive numbers will be determined
print("Difference between consecutive numbers of the said list:")

# Call the 'diff_consecutive_nums' function with 'nums1' and print the result
print(diff_consecutive_nums(nums1))

# Create a list 'nums2' containing numbers
nums2 = [4, 5, 8, 9, 6, 10]

# Print a message indicating the original list
print("\nOriginal list:")
# Print the contents of 'nums2'
print(nums2)

# Print a message indicating that the differences between consecutive numbers will be determined
print("Difference between consecutive numbers of the said list:")

# Call the 'diff_consecutive_nums' function with 'nums2' and print the result
print(diff_consecutive_nums(nums2)) 

Sample Output:

Original list:
[1, 1, 3, 4, 4, 5, 6, 7]
Difference between consecutive numbers of the said list:
[0, 2, 1, 0, 1, 1, 1]

Original list:
[4, 5, 8, 9, 6, 10]
Difference between consecutive numbers of the said list:
[1, 3, 1, -3, 4]

Flowchart:

Flowchart: Find the difference between consecutive numbers in a given list.

For more Practice: Solve these Related Problems:

  • Write a Python program to compute the cumulative sum of a list.
  • Write a Python program to find the sum of consecutive elements in a list.
  • Write a Python program to extract only increasing or decreasing sequences.
  • Write a Python program to find the index where the largest difference occurs.

Go to:


Previous: Write a Python program to extract specified number of elements from a given list, which follows each other continuously.
Next: Write a Python program to compute average of two given lists.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.