List Comprehension as Compulsory Functional Style

I will try to not make my reply too long.

I have to admit that my reaction which started this, was probably too strict:

It is my point of view how readable code should look like. I still strongly stand by this statement: Please do not misuse comprehensions as another way to write a for loop.


The principles of readability and intended use I see as the “Pythonic” way. I do not think that the intended use should be followed always but I think in both the examples there should not be modification of the input data inside the comprehension.

Yes, but when you start with these facets too early, it is called premature optimization. In Python I prefer readability. It is important especially in cases when the code should be well understood by someone else. (It is certainly the case of code in this forum.)

When the optimization causes the code to be less readable, it should be well explained in comments.

I still think the readability will suffer if you go away from the original intention how to use comprehensions. You do not need to be prohibited from doing something to feel that it is not a good way.

Yes, but I certainly understand the statement in the context that it is for the cases when the shorter code improves readability. I am convinced that this only happens when the comprehensions are not too complex.

In general I think that the urge to squeeze a lot of code to small number of lines is a very bad practice. It is good for puzzles like code-golfing though. :slight_smile: How much time do you need to analyze the following code?

from functools import reduce
print(*filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
map(lambda x,y=y:y%x,range(2,int(pow(y,.5)+1))),1),range(2,1000))))

Solution and source: Programming FAQ — Python 3.12.1 documentation

As they said:

Don’t try this at home, kids!

My conclusion: In Python readability first :slight_smile: