Test for consecutive numbers in list
<p>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).</p>

<p>If there are repeated elements, the function should return False.</p>

<p>Here is my attempt to solve this:</p>

<pre><code>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
    else:
        return False
</code></pre>

<p>For example:</p>

<pre><code>l = [-2,-3,-1,0,1,3,2,5,4]

print(isconsecutive(l))

True
</code></pre>

<p>Is this the best way to do this?</p>

<p>Here is another solution:</p>

<pre><code>def is_consecutive(l):
    setl = set(l)
    return len(l) == len(setl) and setl == set(range(min(l), max(l)+1))
</code></pre>

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

<p>Note that you can always simplify</p>

<pre><code>if boolean_expression:
    return True
else:
    return False
</code></pre>

<p>by</p>

<pre><code>return boolean_expression
</code></pre>

python list python-3.x