I suppose that theoretically you could contrive to use a generator comprehension in order to avoid creating a large list in memory:
for _ in (print(i) for i in l if i > 0): pass
(maybe also using some function that does the consuming of values from the generator, so that any loop is hidden away inside that function).
However, not only is this less readable than the explicit for
loop, the plain for
loop is also quicker.
import time
l = [1, -1, 1, 0, 2]
# we don't really want lots of output for this timing test
def dont_really_print(i):
return i
t1 = time.time()
for x in range(1000000):
for i in l:
if i > 0:
dont_really_print(i)
t2 = time.time()
for x in range(1000000):
for _ in (dont_really_print(i) for i in l if i > 0):
pass
t3 = time.time()
print(f"generator comprehension {t3 - t2:.3f} "
f"explicit loop {t2 - t1:.3f}")
gives:
generator comprehension 0.629 explicit loop 0.423