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?)
One main benefit of using a list comprehension in Python is that it's a single tool that you can use in many different situations. In addition to standard list creation, list comprehensions can also be used for mapping and filtering. You don't have to use a different approach for each scenario.
Python list comprehensions are not lazy, though. If you generate [for x in xrange(1, 10000)] you'll get 10000 elements in your list. My understanding is that LINQ list comprehensions are that.
List comprehensions are faster than loops in general. It achieves to be faster by loading the entire list into the memory. There is a downside of this approach when working with large lists (e.g. 1 billion elements).
Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With