What distinguishes a from b?
a = any(x for x in range(4) if x > 0)
b = any(x > 0 for x in range(4))
print(a)
print(b)
What distinguishes a from b?
a = any(x for x in range(4) if x > 0)
b = any(x > 0 for x in range(4))
print(a)
print(b)
Run the list comprehensions separately in a Python REPL and you’ll see.
valuesA = [x for x in range(4) if (x > 0)]
valuesB = [x > 0 for x in range(4)]
print(valuesA)
print(valuesB)
a = any(valuesA)
b = any(valuesB)
print(a)
print(b)
[1, 2, 3]
[False, True, True, True]
True
True
Which ‘function’ takes longer to compute between a and b?
Spyder code profiler gives b running longer than a.
a = any(x for x in range(4) if x > 0) [800 ns]
b = any(x > 0 for x in range(4)) [1100 ns]
I haven’t run timeit
from the command line.
With a deliberate worst-case scenario:
>>> def case_a():
... a = [x for x in range(10000) if x>=99999]
... return any(a)
...
>>> def case_b():
... b = [x >= 99999 for x in range(10000)]
... return any(b)
...
>>> timeit.timeit(case_b, number=1000)
0.23579104198142886
>>> timeit.timeit(case_a, number=1000)
0.13718337495811284
>>>
9999
????
10000 - 1
I purposefully made the test to return False, so the value tested against is larger than the top of the range.
ok - i thought you would love to have the last item be the hit …
as you also used >= instead of >
I’ve heard that Python is elegant. Is this what they meant to say?
print({x for x in range(-100, 100) if any(abs(x**2 - 4) - abs(x**3 / 3) == y for y in range(-100, 100))})