January 2, 2022
Why I use list comprehension in python less now
I love python. I try to use it as often as I can. It's a great language, and very flexible with whatever I need it to do.
[x for x in array if x is True]
These days however, as I code more and more for the public, I find myself using list comprehension (above) less and less. Why? It's harder for beginners to understand, and can obscure the logic of my code.
About List Comprehension
List comprehension, or "inline loops" in python is one of the things I love about it.
numbers = [x for x in range(0, 25)]
It's a great way to quickly generate a list, or a dictionary. It's pretty flexible too:
numbers_with_a_1 = [x for x in range(0, 25) if '1' in str(x)]
but it can quickly get out of hand. While the syntax might be easy for you to understand, and might fit on one line, keep in mind that you're often not the only person reviewing this code.
I'm very much guilty of overusing it, since it's one of those things about python I absolutely love - but it's important, especially in shared or public projects, to take a step back and code something in a more beginner-friendly way.
An Example
This is a simplified example, but if I wanted to generate a list of numbers containing the number 1, (1, 100, 14, 15, 21, etc.) I might do something like this. It's a one-line function, and for me, very easy to read - but that might not be the case for a beginner.
def get_numbers_with_a_1(start=0, stop=25):
return [x for x in range(start, stop) if '1' in str(x)]
For someone else, this might be easier for understanding the function's logic.
def get_numbers_with_a_1(start=0, stop=25):
numbers = []
for number in range(start, stop):
if '1' in str(number):
numbers.append(number)
return numbers
Syntactic sugar is great; but when programming in a shared environment, try to think of those that are just getting started.
Let's Work Together
I help organizations solve complex technical challenges, in the simplest ways possible.