In Python, Is An "and" Statement Or All() Faster?
Solution 1:
and
s are faster, there is no list creation and no function call.
In [10]: %timeit '1234'.isdigit() and '4567'.isdigit() and '7890'.isdigit()
1000000 loops, best of 3: 186 ns per loop
In [11]: %timeit all(['1234'.isdigit(), '4567'.isdigit(), '7890'.isdigit()])
1000000 loops, best of 3: 323 ns per loop
and
s wouldn't even unnecessarily evaluate things:
In [1]: def x():
...: print 'call'
...: returnFalse
...:
In [2]: x() and x()
callOut[2]: FalseIn [3]: all([x(), x()])
callcallOut[3]: False
Solution 2:
The second one evaluates all of the conditions, puts those boolean values into a list and then checks to see if they're all true.
The first, on the other hand, just checks them all one-by-one and stops at the first false condition (if there is one). The first one is definitely faster, as Pavel's answer shows.
You could also use a generator, which lets all
short-circuit:
all(str.isdigit(s) for s in your_strings)
Solution 3:
If you really want the fastest way to deal with 3 static values, and the dozens of nanoseconds of difference actually matters in your code:
ifTrue:
print"All are digits!"
Or, even faster:
print"All are digits!"
In any case where the performance matters in the slightest, you will have a large and/or dynamic set of values, and you simply can't do that with and
, except by creating an explicit for
loop:
value = Truefor s in strings:
value = value and s.isdigit()
if not value:
breakif value:
print"All are digits!"
And you can immediately see how the and
isn't helping things at all:
for s in strings:
if not s.isdigit():
breakelse:
print"All are digits!"
But if you want to do things faster with all
, you can use a generator expression (or a map
/imap
call) instead of a list comprehension, and it's just as fast, and readable, with a large, dynamic sequence as with a small, static one:
ifall((x.isdigit() for x in ('1234', '4567', '7890')):
print"All are digits!"ifall((x.isdigit() for x in strings):
print"All are digits!"
If the sequence is very big, and it's possible that some of the values are false, this will be hugely faster than anything involving building a list
of all of the True/False values.
Post a Comment for "In Python, Is An "and" Statement Or All() Faster?"