by tlocke · 3y ago · 0 comments
sum(1 for age in ages if age > 17)
with the other method you're treating a boolean as an int. Weak typing.[1]: https://docs.python.org/3/library/functions.html?highlight=s...
[2]: https://docs.python.org/3/library/stdtypes.html#boolean-valu...
if 23:
print('hello')
and it'll print 'hello'. But I'd prefer a strongly typed approach where this code would give an error saying, 'a bool is expected here'. Sure it's a subjective thing, and this is just my preference.“I don’t know the type hierarchy used in language X” is not the same thing as “language X is weakly typed”.
Python 3.11.4 (tags/v3.11.4:d2340ef, Jun 7 2023, 05:45:37) [MSC v.1934 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(True, int)
True
>>> isinstance(False, int)
True
>>> issubclass(bool, int)
True sum(int(age > 17) for age in ages)
Every nanosecond is vital! python -m timeit 'sum(1 for age in range(100000) if age > 17)'
50 loops, best of 5: 5.08 msec per loop
python -m timeit 'sum(int(age > 17) for age in range(100000))'
50 loops, best of 5: 7.96 msec per loop
python -m timeit 'sum(age > 17 for age in range(100000))'
50 loops, best of 5: 4.78 msec per loopPlus here on each iteration `int` has to be loaded from the globals before it can be called.