DEV Community

Discussion on: Ditch These 7 Bad Habits in Python

Collapse
steelwolf180 profile image
Max Ong Zong Bao • Edited on

Tbh I don't really use list compensation because it suffers from being too clever but ignores readability and debugging.

Take for example this that you wrote a as good example.

def generate_fruit_basket_lc(fruits):
"""With list comprehension"""
return [fruit for fruit in fruits if fruit != "grapes"

What if you were to encounter a bug in this code.

How would you debug it? Would you spend more time figuring out what went wrong by looking at the logic or debug it step by step?

But because you put it as one liner it become difficult to understand or debug in a step by step process.

Collapse
romansorin profile image
Roman Sorin

List comprehension is one of my favorite tools for writing effective statements and fewer lines, but it needs to be done right. The example is likely slightly exaggerted (the
"fruit for fruit in fruits" bit), but I've seen it done. I believe they are more readable and easier to understand if the names of variables/elements are chosen properly — but we know that naming is the hardest thing :)

Collapse
jerrynsh profile image
Jerry Ng Author • Edited on

A long and complex list comprehension definitely suffers from being too "smart" and thus ignores readability.

However, when it comes to a short for loop, i.e. generating a list of numbers from a range, no one should be using a regular for loop with append .

# This is way more readable
nums = [i for i in range(10)]

# This is less readable, IMO we shouldn't have to do this
nums = []

for i in range(10):
    nums.append(i)
Enter fullscreen mode Exit fullscreen mode

Throwing in a single conditional if (i.e. the grapes example in the post) is fine IMHO. It really depends on what you and your team agree on at the end of the day. Nothing beats a good consistency in a shared codebase.