 Open in App
Not now

# Python | Check if list contains consecutive numbers

• Last Updated : 02 Jan, 2023

Given a list of numbers, write a Python program to check if the list contains consecutive integers. Examples:

```Input : [2, 3, 1, 4, 5]
Output : True

Input : [1, 2, 3, 5, 6]
Output : False```

Let’s discuss the few ways we can do this task.

Approach #1 : using sorted() This approach uses sorted() function of Python. We compare the sorted list with list of range of minimum and maximum integer of the list and return it.

## Python3

 `# Python3 Program to Create list``# with integers within given range` `def` `checkConsecutive(l):``    ``return` `sorted``(l) ``=``=` `list``(``range``(``min``(l), ``max``(l)``+``1``))``    ` `# Driver Code``lst ``=` `[``2``, ``3``, ``1``, ``4``, ``5``]``print``(checkConsecutive(lst))`

Output:

`True`

Approach #2 : Using numpy.diff() Numpy module provides a function diff() that calculate the n-th discrete difference along the given axis. We find the iterative difference of the sorted list and check if it is equal to 1.

## Python3

 `# Python3 Program to Create list``# with integers within given range``import` `numpy as np` `def` `checkConsecutive(l):``    ``n ``=` `len``(l) ``-` `1``    ``return` `(``sum``(np.diff(``sorted``(l)) ``=``=` `1``) >``=` `n)``    ` `# Driver Code``lst ``=` `[``2``, ``3``, ``1``, ``4``, ``5``]``print``(checkConsecutive(lst))`

Output:

`True`

Approach #3 :

To check if a list contains consecutive numbers, you can use the following approach:

1. Sort the list. This step is necessary because we want to check if the numbers in the list are consecutive, not their order.
2. Use a list comprehension to check if all elements in the sorted list are consecutive. If all elements are consecutive, then the list comprehension will return a list of True values. Otherwise, it will return a list with at least one False value.
3. Use the all() function to check if all elements in the list are True. If all elements are True, then the list contains consecutive numbers. Otherwise, the list does not contain consecutive numbers.

Here is an example of how you can use this approach:

## Python3

 `#given list``lst ``=` `[``2``, ``3``, ``1``, ``4``, ``5``]` `#sort the list``sorted_lst ``=` `sorted``(lst)` `#check if all elements are consecutive``is_consecutive ``=` `all``(sorted_lst[i] ``=``=` `sorted_lst[i``-``1``] ``+` `1` `for` `i ``in` `range``(``1``, ``len``(sorted_lst)))` `#print the result``print``(is_consecutive) ``# prints True``#This code is contributed by Edula Vinay Kumar Reddy`

Output

`True`

This approach has a time complexity of O(n log n) because it sorts the list using the built-in sorted() function, which has a time complexity of O(n log n) in the worst case. It also has a space complexity of O(1) because it does not create any additional data structures.

My Personal Notes arrow_drop_up