3 ms·
This is true, but in code reviews and such, it often boils down to familiarity above anything else, like someone preferring names = [] for record in re
by tehnub 2y ago
This is true, but in code reviews and such, it often boils down to familiarity above anything else, like someone preferring
names = []
for record in records:
names.append(record["name"])
to
names = [record["name"] for record in records]
Now, I might say something if I saw this:
import operator
names = list(map(operator.itemgetter("name"), records))
Seems a bit unidiomatic given that list comprehensions are in the language... but probably many disagree.
- akasakahakada 2y agolist-map-itemgetter is actually the fastest solution in Python. Should actually promote this.
- amanzi 2y agoGreat 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.
- hleszek 2y agoA simple list comprehension is quite readable and better IMHO. It is very common and most people will understand directly what it does. Of course, when you have multiple levels or complex lambdas inside, then I agree that the for loop might be preferable.
- VTimofeenko 2y agoI'd say it also heavily depends on the code style that's internal to the project. Case in point, for heavy toolz users: list(toolz.pluck("name", records))
- sgarland 2y agoI’m convinced that the only reason the operator library exists is to provide inputs for functools, which itself is mostly there to pretend that you’re a functional programmer. …but I do kinda like map().