3 ms·
Great example. My personal preference is the first one, but I put that down to me being inexperienced and not working in a professional development environment.
by amanzi 2y ago
Great example. My personal preference is the first one, but I put that down to me being inexperienced and not working in a professional development environment.
I've been using Ruff with most of the rules enabled, and they have a page for this scenario here: https://docs.astral.sh/ruff/rules/manual-list-comprehension/ https://docs.astral.sh/ruff/rules/manual-list-comprehension/
Another one that trips me up is the ternary operator: https://docs.astral.sh/ruff/rules/if-else-block-instead-of-if-exp/ https://docs.astral.sh/ruff/rules/if-else-block-instead-of-i... I prefer the longer, more verbose version, even though the suggestion looks more clever.
- aidos 2y agoLet me see if I can sway you. The nice thing about both the ternary and the list compression is that they become statements of the form derived_thing = some_computation. The code flows better when you’re skimming it at a high level and thinking “then we get this”, “then pluck this”. You can think more about your reformed data and less about how it was reformed. The alternative is that the branching obscures what you’re trying to create at each step. Sometimes I’ll even use 2 list comprehensions instead of a loop (even though it’s slower) because it’s clearer to read something like: odds = […] evens = […] That’s my experience, anyway.
- akasakahakada 2y agoThis is my choice. So easy to get lost in the sea of intermediate veriables inside a loop. If stuff can be rewriten in list comprehensive separately then I will do it.