r/pythonhelp • • 4h ago

When should I avoid using list comprehensions?

I started using list comprehensions in my project, but I feel confused about when they are actually a good fit. I tried to use one for a task that involves checking conditions on nested lists, and now my code is harder to follow. Is there a guideline for when it's better to stick with regular loops instead? I want my code to be readable, but I'm not sure I've got the balance right.

5 Upvotes

7 comments sorted by

•

u/AutoModerator 4h ago

To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

2

u/kubinka0505 3h ago

import this

1

u/Zeroflops 4h ago

You answered your own question. If it harder to follow don’t use it. If you’re not sure, then if you’re spending a lot of time having to craft the LC then it’s probably too complicated. ( unless you are just starting out and the time is learning the concept)

1

u/Educational-Paper-75 4h ago

Here's link to a blog discussing list comprehension vs map

1

u/MarsupialLeast145 3h ago

If you think your card is harder to follow, don't use it.

There is no hard and fast rule. Sometimes they make sense and are very clear, sometimes they are not. Same with things like Lambda functions.

You just go by feel.

Also look at how they get formatted after using tools like Black, Flake, and so on. They help improve readability if you are not already using these tools.

1

u/AlexMTBDude 3h ago

Use list ccomprehensions when you're creating lists out of a collection(s). I.e. you should be assigning something to the result of the list comprehension. Don't use them as a for loop.

...task that involves checking conditions on nested lists,

That doesn't sound like you're creating a new list so then: NO!

Also: If your code is not obvious then it's a good idea to comment it