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:
squares = [item ** 2 for item in some_list]
For loops are better for doing something with the elements of a list (or other objects):
for item in some_list:
print(item)
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 append
calls required for creating a list are still ugly. Instead, refactor into a function:
def polynomial(x):
return x ** 4 + 7 * x ** 3 - 2 * x ** 2 + 3 * x - 4
result = [polynomial(x) for x in some_list]
Only if you're concerned about speed – and you've done your profiling! – you should keep the long, unreadable list comprehension.
It's not considered bad.
However, list comprehensions that either
- Have side effects, or
- Are more readable as a multi-line for loop
are generally frowned upon.
In other words, readability is important.
As an overly contrived example of the first bad example:
x = range(10)
[x.append(5) for _ in xrange(5)]
Basically, if you're not storing the result, and/or it modifies some other object, then a list comprehension is probably a bad idea.
As an example of the second, have a look at pretty much any code golf entry written in python. Once your list comprehension starts to become something that isn't readable at a glance, consider using a for loop.
There is no performance hit (even if there were, I would not worry about it; if performance were so important, you've got the wrong language). Some frown upon list comprehensions because they're a bit too terse for some, that's a matter of personal preference. Generally, I find simple list comprehensions to be much more readable than their loop/condition equivalents, but when they start to get long (e.g. you start to go past 80 characters), they might be better replaced with a loop.