

Ask HN: Constant List predicate in python? - RiderOfGiraffes

Here's something I had to write in a hurry yesterday, and I haven't had time to spend to find the "right" technique.  So I'd be interested to hear the thoughts of the hackers around here.<p>Write a routine that returns True iff all the elements of the input list are equal.<p>Here's a non-pythonic routine:<p><pre><code>  def is_constant(l):
    for i in range(1,len(l)):
      if l[0]!=l[i]:
        return False
    return True
</code></pre>
That's a simple, early-terminating imperative loop.  Here's a slower and not necessarily clearer version:<p><pre><code>  def is_constant(l):
    return min(l)==max(l)
</code></pre>
Personally, the fact that the code is short really appeals to me, but some people would find it unclear in how (and why!) it works.<p>Here's an even less clear version:<p><pre><code>  def is_constant(l):
    return len(l)*[True]==[ l[0]==a for a in l ]
</code></pre>
I'd specifically like to know the answer to this question:  Suppose you have to maintain a piece of code that performs this function.  What would your ideal code be to find?<p>Extra marks available for code that deals cleanly with corner cases: empty lists, tuples and generators.
======
balding_n_tired
Of course, this will run through the whole list, no matter what...

    
    
      def is_constant(l):
          return reduce(lambda x, y: x and (y == l[0]), l, True)

------
gms
return (len(set(l)) == 1)

~~~
yan
I'd pick this solution.

------
makecheck
def f(x): return not x or x == [x[0]] * len(x)

~~~
RiderOfGiraffes
Small, clean, clear. Fails for tuples. One could use:

    
    
        def f(x): return not x or list(x) == [x[0]] * len(x)
    

Does have the downside that it constructs a list, which the min==max solution
doesn't.

I wonder if there is a single "ideal" solution ...

~~~
makecheck
This works for a list of numbers (array or tuple), as long as numbers aren't
negative:

def f(x): 0 == sum([y - x[0] for y in x])

