On Jul 26, 2019, at 05:51, Eli Berkowitz email@example.com wrote:
#1 for item in lst: print(item)
# 2 [print(item) for item in lst]
# 3 for item in lst: print(item)
Normally, expressions are about producing a value, and if you only care about side effects, you want a statement. That’s why #3 is better than #2, beyond the watered memory.
Sometimes you want to violate guidelines like that, but in that case it’s usually worth explicitly marking that you're doing so. Which you can do easily and concisely in today’s Python:
#4 consume(print(item) for item in lst)
This signals that you’re iterating the iterator for side effects, rather than to build a value, and it’s nicely concise.
You need to write that consume function (or just borrow it from the itertools docs), but it’s a trivial one-liner you can write once, and you can choose whether you want clarity:
def consume(it): for _ in it: pass
… or performance:
def consume(it): colllections.deque(it, maxlen=0)