When “not” to use list comprehensions

Ivjot Singh
3 min readFeb 5, 2020

--

Photo by Roman Synkevych on Unsplash

But why isn’t is too pythonic?

Let’s first understand what pythonic code is with a use case of the list comprehension.
(Hitting two targets with one arrow #lazy)

When you use the common/famous Python idioms well, that’s pythonic code (examples mentioned below will help you understand better)

Problem — Make a list containing the squares of another list

Non-Pythonic code

Now solving the same problem using list comprehension.

Pythonic code

Clearly using list comprehensions here is more pythonic and hence clean code following zen of python well enough.

But everything in excess sucks.
So coming at the main point.

When not to use List Comprehensions

1: Creating unnecessary work for the garbage collector.

Let say you have to add all the numbers from 0 to 1000.
Here you can use List comprehension as:

Using list comprehension

But here we are wasting too much memory for storing the list rather we can yield every number one at a time and add it (and here comes generator)

Using generators instead of saving in a list

more on generators

2: Anti-pattern

I noticed an anti-pattern among beginners, like this:

[ print(i) for i in some_iterable ]

i.e: They are not interested in creating a list, but use the comprehension syntax for getting the cool python developer tag instead of using a classic loop.

for i in some_iterable:
print(i)

which is actually avoiding creating a list full of None.

3: Flattening

Let say you have to flatten a 3X3 matrix to a single list you can use list comprehension as:

Agree the code is a single line and quite cool but it’s against a very important Zen Of Python and that is code readability
The code you write should be easily understood by fellow programmers so again sticking to basics will help here.

The code complexity is the same as above

Fun fact- set and dictionary comprehensions also exists :p

So it’s not important to be cool all the time, sometimes sticking to the basics help both in programming and life!

ps- Efforts are never futile (slow progress > no progress)

📝 Read this story later in Journal.

👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.

--

--