The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Question
00:43 Accepted answer (Score 24)
00:53 Answer 2 (Score 11)
01:10 Answer 3 (Score 3)
01:36 Answer 4 (Score 2)
01:47 Thank you

--

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

Answer 1 links:
http://docs.python.org/library/functions...
http://docs.python.org/library/functions...

--

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)