Why is python list comprehension sometimes understood?

Many of the developers I've met suggest using simple loops and conditions rather than expressions to describe strings.

I always found them very powerful, since I can put a lot of code on one line, and this saves a lot of variables. Why is it still considered bad practice?

(slow?)

+6
source share
3 answers

When creating lists, lists are used, for example:

squares = [item ** 2 for item in some_list] 

For loops, it's better to do something with list items (or other objects):

 for item in some_list: print(item) 

Using comprehension for its side effects or for-loop to create a list is usually underestimated.


Some of the other answers here advocate turning understanding into a cycle when it gets too long. I don't think good style: the append calls needed to create a list are still ugly. Instead, reorganize 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 are concerned about speed - and you have done your profiling! - You must keep a long, unreadable understanding of the list.

+20
source

This is not considered bad.

However, list either

  • There are side effects, or
  • More readable as multi-line for loop

generally not approved.

In other words, readability is important.

As an overly far-fetched example of the first bad example:

 x = range(10) [x.append(5) for _ in xrange(5)] 

In principle, if you do not save the result and / or do not modify any other object, then understanding the list is probably a bad idea.

As an example of the second, take a look at almost any entry in the code field written in python. Once your understanding of the list begins to become something that cannot be read at a glance, consider using a for loop.

+6
source

There is no performance (even if it were, I would not worry about it, if performance was so important, you have the wrong language). Some are unhappy with the understanding of the lists, because some of them are too short for some, it is a matter of personal preference. As a general rule, I find that simple list representations are more readable than their loop / condition equivalents, but when they start to get long (for example, you start to skip over 80 characters), they can be better replaced by a loop.

+4
source

Source: https://habr.com/ru/post/901132/


All Articles