Many developers I have met suggest it’s best practice to go with simple loops and if conditions instead of one line list comprehension statements.
I have always found them very powerful as I can fit a lot of code in a single line and it saves a lot of variables from being created. Why is it still considered a bad practice?
(Is it slow?)
List comprehensions are used for creating lists, for example:
For loops are better for doing something with the elements of a list (or other objects):
Using a comprehension for its side effects, or a for-loop for creating a list, is generally frowned upon.
Some of the other answers here advocate turning a comprehension into a loop once it becomes too long. I don’t think that’s good style: the
appendcalls required for creating a list are still ugly. Instead, refactor into a function:Only if you’re concerned about speed – and you’ve done your profiling! – you should keep the long, unreadable list comprehension.