3 ms·
Ask HN: Constant List predicate in python?
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.
Write a routine that returns True iff all the elements of the input list are equal.
Here's a non-pythonic routine:
def is_constant(l):
for i in range(1,len(l)):
if l[0]!=l[i]:
return False
return True
That's a simple, early-terminating imperative loop. Here's a slower and not necessarily clearer version:
def is_constant(l):
return min(l)==max(l)
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.
Here's an even less clear version:
def is_constant(l):
return len(l)*[True]==[ l[0]==a for a in l ]
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?
Extra marks available for code that deals cleanly with corner cases: empty lists, tuples and generators.
- makecheck 17y agodef f(x): return not x or x == [x[0]] * len(x)
- RiderOfGiraffes 17y agoSmall, 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 17y agoThis 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])
- gms 17y agoreturn (len(set(l)) == 1)
- yan 17y agoI'd pick this solution.
- deleted 17y ago[deleted]
- deleted 17y ago[deleted]
- yan 17y agoAh, you're right. A lapse of judgment and test cases led me to write that. Please disregard.
- deleted 17y ago[deleted]
- RiderOfGiraffes 17y agoAnd this comment to which I'm replying, and I'll delete this one ...
- balding_n_tired 17y agoOf 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)