I am looking for a better way, may be using list comprehensions?
>>> x = [1, 1, 1, 1, 1, 1]
>>> x
[1, 1, 1, 1, 1, 1]
>>> for i in x:
... if i!=1:
... print "fail"
...
>>>
>>> x = [1, 1, 1, 1, 1, 0]
>>> for i in x:
... if i!=1:
... print "fail"
...
fail
>>>
This uses the function
allwith a generator expression.If you always have only zeroes and ones in the list (or if you want to just check if the list doesn’t have any zeroes), then just use
allwithout any additional tricks:Benchmark of some solutions:
The numbers mean what time in milliseconds it took to run the solution once (average of 1000
timeitruns)Python 3.2.3
Python 2.7.3
[PyPy 1.9.0] Python 2.7.2
The following test cases were used:
WAmeans that the solution gave a wrong answer;REstands for runtime error.So my verdict is, Winston Ewert‘s
x==[1]*len(x)solution is the fastest in most cases. If you rarely have lists of all ones (the data is random, etc.) or you don’t want to use additional RAM, my solution works better. If the lists are small, the difference is negligible.