Vermillion Vermillion - 8 days ago 4x
Python Question

Test for consecutive numbers in list

I have a list that contains only integers, and I want to check if all the numbers in the list are consecutive (the order of the numbers does not matter).

If there are repeated elements, the function should return False.

Here is my attempt to solve this:

def isconsecutive(lst):
Returns True if all numbers in lst can be ordered consecutively, and False otherwise
if len(set(lst)) == len(lst) and max(lst) - min(lst) == len(lst) - 1:
return True
return False

For example:

l = [-2,-3,-1,0,1,3,2,5,4]



Is this the best way to do this?


Here is another solution:

def is_consecutive(l):
    setl = set(l)
    return len(l) == len(setl) and setl == set(range(min(l), max(l)+1))

However, your solution is probably better as you don't store the whole range in memory.

Note that you can always simplify

if boolean_expression:
    return True
    return False


return boolean_expression