On Fri, 26 Jul 2019 at 13:55, Eli Berkowitz email@example.com wrote:
Say you have a list and you want to perform some operation on each item in the list - but you don't need to store the result in a list.
There are three simple ways of doing this, at least as far as I know: ([print(item)] could be any expression, just using it as an example)
lst = [1, 2, 3, 4] #1 for item in lst: print(item) # 2 [print(item) for item in lst] # 3 for item in lst: print(item)
#1 - In my opinion, this should be a one line operation so #1 is not ideal. #2 - It also shouldn't require storing results in array, to save time/memory, so #2 is out. #3 - I think #3 is just not good syntax, it seems very unpythonic to me - it breaks the norm that blocks go on their own lines. It does seem the best of the three though and I know my assessment is kind of subjective.
#1 and #3 are the same (in terms of statement structure) and I see no reason to treat them differently. (#2 is significantly different, in that it retains all the intermediate values, and can only be used for expressions).
In #1 you say "this should be a one line operation" - but there's no particular reason why it "should". If it should, then #3 *is* the appropriate one-line version. In #3 you say it "is just not good syntax", and yet you said above that the statement "should" be a one-liner. The only thing that is "not good" about #3 over #1 is that it's a one-liner...
I'm wondering if a possible alternative syntax could be a for-expression, like there's if-expressions, which always evaluates to None:
print(item) for item in lst
This seems to me to be no better than #3, and worse in the sense that it isn't currently valid, whereas #3 is. I think you should simply accept that #3 is entirely valid and acceptable syntax. I use it fairly regularly, where appropriate (which isn't often - #1 *is* typically better - but it's certainly all of the cases where your proposed new syntax would be useful).