On Jul 26, 2019, at 05:51, Eli Berkowitz <eliberkow...@gmail.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)

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/FBDC4PKOO7A3VOW5GY7JFH46ZKTCAASC/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to