-2

I see a lot around the indication of using list comprehension in Python programming. It is often claimed that it is better than the traditional for loop.

From what I've studied, list comprehension is sort of a single-line for loop.

Is there some kind of gain when using list comprehension instead of a traditional for loop?

In terms of readability, it seems to me to be less understandable than a traditional for, especially when you increase the complexity with if/else and other expressions.

Everton da Rosa
  • 117
  • 1
  • 3
  • 1
    Not sure what you would consider a gain. List comprehensions are ultimately syntactic sugar around loops and append – just like an equivalent `for` loop is ultimately syntactic sugar around loops and append. Whether it is more readable is opinion based, but I'd wager you are in a minority when you consider a list comp less readable – at least for straightforward cases. – MisterMiyagi Jun 01 '22 at 12:28
  • Does this answer your question? [In Python, is it better to use list comprehensions or for-each loops?](https://stackoverflow.com/questions/2849645/in-python-is-it-better-to-use-list-comprehensions-or-for-each-loops) – mkrieger1 Jun 01 '22 at 12:30
  • List comprehensions have the *possibility* of being highly optimised by the compiler, while a loop is pretty much stuck with calling `list.append` many times with all the associated overhead. Whether the compiler actually does anything with that is another question though… And as with anything else, shorter code is *not* always more readable, but when it is then it is. – deceze Jun 01 '22 at 12:31
  • Does this answer your question? [Are list-comprehensions and functional functions faster than "for loops"?](https://stackoverflow.com/questions/22108488/are-list-comprehensions-and-functional-functions-faster-than-for-loops) – MisterMiyagi Jun 01 '22 at 12:31
  • Ignoring side effects for the moment, a list comprehension can *only* create a list; the `for` loop could be doing a lot of other things, and you may have to read the loop carefully to verify that all it does is populate a list. – chepner Jun 01 '22 at 12:35
  • You might ask the same about `lambda` functions, or many other language features. Is there a *real* advantage? You *can* write pretty much everything with more primitive constructs after all. You could write in Assembly, really. But, well, there's a reason most people don't. Because more expressive code is an advantage in and of itself. – deceze Jun 01 '22 at 12:35
  • 2
    `[i * i for i in range(10)]` is imho more readable than the corresponding `for` loop. – luk2302 Jun 01 '22 at 12:37

0 Answers0