Python Practice › List Programs › Program 65

Differences between neighbours

EasyList Programs · 65 of 100

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

Advertisement
Input
[1, 1, 3, 4, 4, 5, 6, 7]
Output
[0, 2, 1, 0, 1, 1, 1]

Approach

  1. zip the list with itself shifted by one.

Solution

Python
numbers = [1, 1, 3, 4, 4, 5, 6, 7]print([b - a for a, b in zip(numbers, numbers[1:])])
Output
[0, 2, 1, 0, 1, 1, 1]

Line by line

Line 2

zip(numbers, numbers[1:]) gives each pair of neighbours.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Leave a Comment