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>A better approach in terms of how many times you look at the elements would be to incorporate finding the <em>min</em>, <em>max</em> and <em>short circuiting</em> on any dupe all in one pass, although would probably be beaten by the speed of the builtin functions depending on the inputs:</p>

<pre><code>def mn_mx(l):
    mn, mx = float("inf"), float("-inf")
    seen = set()
    for ele in l:
        # if we already saw the ele, end the function
        if ele in seen:
            return False, False
        if ele &lt; mn:
            mn = ele
        if ele &gt; mx:
            mx = ele
        seen.add(ele)
    return mn, mx

def isconsecutive(lst):
    """
    Returns True if all numbers in lst can be ordered consecutively, and False otherwise
    """
    mn, mx = mn_mx(lst)
    # could check either, if mn is False we found a dupe
    if mn is False:
        return False
    # if we get here there are no dupes
    return mx - mn == len(lst) - 1
</code></pre>

python list python-3.x