Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is python list comprehension sometimes frowned upon?

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?)

like image 411
Optimus Avatar asked Nov 09 '11 16:11

Optimus


People also ask

Is list comprehension important in Python?

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.

Are list comprehensions lazy Python?

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.

Why might you use a list comprehension instead of a loop in Python?

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).

Are list comprehensions better than for loops?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.


1 Answers

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.

like image 79
Petr Viktorin Avatar answered Oct 03 '22 14:10

Petr Viktorin