Check if list contains consecutive numbers in Python

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

Depending on the needs of our data analysis we may need to check for presence of sequential numbers in a python data container. In the below programs we find out if among the elements of Alist, there are any consecutive numbers.

With range and sorted

The sorted function will rearrange the elements of the list in a sorted order. We then apply the range function taking the lowest and highest numbers form the list using min and max functions. We store the results of above operations in two lists and compare them for equality.

Example

Live Demo

listA = [23,20,22,21,24]
sorted_list = sorted(listA)
#sorted(l) ==
range_list=list(range(min(listA), max(listA)+1))
if sorted_list == range_list:
print("listA has consecutive numbers")
else:
print("listA has no consecutive numbers")

# Checking again
listB = [23,20,13,21,24]
sorted_list = sorted(listB)
#sorted(l) ==
range_list=list(range(min(listB), max(listB)+1))
if sorted_list == range_list:
print("ListB has consecutive numbers")
else:
print("ListB has no consecutive numbers")

Output

Running the above code gives us the following result −

listA has consecutive numbers
ListB has no consecutive numbers

With numpy diff and sorted

The diff function in numpy can find the difference between each of the numbers after they are sorted. We take a sum of this differences. That will match the length of the list if all numbers are consecutive.

Example

Live Demo

import numpy as np
listA = [23,20,22,21,24]

sorted_list_diffs = sum(np.diff(sorted(listA)))
if sorted_list_diffs == (len(listA) - 1):
print("listA has consecutive numbers")
else:
print("listA has no consecutive numbers")

# Checking again
listB = [23,20,13,21,24]
sorted_list_diffs = sum(np.diff(sorted(listB)))
if sorted_list_diffs == (len(listB) - 1):
print("ListB has consecutive numbers")
else:
print("ListB has no consecutive numbers")

Output

Running the above code gives us the following result −

listA has consecutive numbers
ListB has no consecutive numbers
Updated on 13-May-2020 14:32:52