The Python Oracle

Pythonic way to check if: all elements evaluate to False -OR- all elements evaluate to True

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Pythonic Way To Check If: All Elements Evaluate To False -Or- All Elements Evaluate To True
00:34 Answer 1 Score 11
00:46 Accepted Answer Score 24
00:53 Answer 3 Score 3
01:11 Answer 4 Score 2
01:16 Thank you

--

Full question
https://stackoverflow.com/questions/4310...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 24


def unanimous(it):
  it1, it2 = itertools.tee(it)
  return all(it1) or not any(it2)



ANSWER 2

Score 11


def all_bools_equal(lst):
    return all(lst) or not any(lst)

See: http://docs.python.org/library/functions.html#all

See: http://docs.python.org/library/functions.html#any




ANSWER 3

Score 3


Piggybacking on Ignacio Vasquez-Abram's method, but will stop after first mismatch:

def unanimous(s):
  it1, it2 = itertools.tee(iter(s))
  it1.next()
  return not any(bool(a)^bool(b) for a,b in itertools.izip(it1,it2))

While using not reduce(operators.xor, s) would be simpler, it does no short-circuiting.




ANSWER 4

Score 2


def all_equals(xs):
    x0 = next(iter(xs), False)
    return all(bool(x) == bool(x0) for x in xs)