- Related Questions & Answers
- Check if list contains all unique elements in Python
- Check if a string contains numbers in MySQL?
- How to check if array contains three consecutive dates in java?
- Check if a binary string contains consecutive same or not in C++
- Check if array elements are consecutive in Python
- Check three consecutive numbers - JavaScript
- Check if absolute difference of consecutive nodes is 1 in Linked List in Python
- Check if Queue Elements are pairwise consecutive in Python
- JavaScript to check consecutive numbers in array?
- Python - Check if a list is contained in another list
- How to check if a Python string contains only digits?
- Python Program to Check If Two Numbers are Amicable Numbers
- Check if list is strictly increasing in Python
- Check if array contains contiguous integers with duplicates allowed in Python
- Check if a string has m consecutive 1s or 0s in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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.

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")

Running the above code gives us the following result −

listA has consecutive numbers ListB has no consecutive numbers

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.

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")

Running the above code gives us the following result −

listA has consecutive numbers ListB has no consecutive numbers

Advertisements