1

Say I need to print all the elements of a list into the console on new lines.

for i in lst:
    print(i)

Is it okay to do this instead?

[print(x) for x in lst]

I know I'm not saving the resulting list this way, but it allows me to shorthand the above example onto one line. Will this create unneccessary grabage in the memory or should this be avoided for some different reason?

Jack Avante
  • 1,405
  • 1
  • 15
  • 32
  • 2
    Yes, this is bad. A list comprehension is used to create a list, not carry out side effects. What your have in the second bit gives a false intent, and creates a list that will never be needed. – Carcigenicate Nov 12 '19 at 14:49
  • 3
    Possible duplicate of [Is it Pythonic to use list comprehensions for just side effects?](https://stackoverflow.com/questions/5753597/is-it-pythonic-to-use-list-comprehensions-for-just-side-effects) – pault Nov 12 '19 at 14:50
  • It does, thanks! Didn't know to use proper language to find the answer to this question. Now I know it's called a list comprehension and side effect – Jack Avante Nov 12 '19 at 14:51
  • 1
    In the second example you create a list of size `len(lst)` filled with `None`. Python will throw the list away after that line because it doesnt have a reference but you are still consuming a lot of memory at that moment in time only because you are trying to one line something that shouldn't be one-lined. This is a big nono – Error - Syntactical Remorse Nov 12 '19 at 14:51
  • 1
    It's not even really shorthand; you've traded a `:` and a newline for the opening and closing brackets. If you are misguidedly desperate for a single line, `for i in list: print(i)` serves the same purpose without creating a list. – chepner Nov 12 '19 at 14:52
  • Oh so it does create garbage. Thanks a lot for the info! – Jack Avante Nov 12 '19 at 14:52
  • Reducing line count, in and of itself, is not a goal. Reducing *complexity* is a goal; a reduced line count is simply a common side effect of reducing complexity. – chepner Nov 12 '19 at 14:54

0 Answers0