sinan sinan - 3 months ago 43
Python Question

Is it Pythonic to use list comprehensions for just side effects?

Think about a function that I'm calling for it's side effects, not return values (like printing to screen, updating GUI, printing to a file, etc.).

def fun_with_side_effects(x):
...side effects...
return y

Now, is it Pythonic to use list comprehensions to call this func:

[fun_with_side_effects(x) for x in y if (...conditions...)]

Note that I don't save the list anywhere

Or should I call this func like this:

for x in y:
if (...conditions...):

Which is better and why?


It is very anti-Pythonic to do so, and any seasoned Pythonista will give you hell over it. The intermediate list is thrown away after it is created, and it could potentially be very, very large, and therefore expensive to create.