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:
if True:
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 = True
for s in strings:
value = value and s.isdigit()
if not value:
break
if 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():
break
else:
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:
if all((x.isdigit() for x in ('1234', '4567', '7890')):
print "All are digits!"
if all((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.