4 ms·
I don't think you can really improve on this. You could use a list comprehension, but that can be unclear and hard to extend, depending on the situation. It ca
by tomn 3y ago
I don't think you can really improve on this.
You could use a list comprehension, but that can be unclear and hard to extend, depending on the situation. It can be a nice option if most of the parts in the generator can be broken out into functions with their own name, though.
You could turn it into a generator, which can cause some fun bugs (e.g. everything works fine when you first iterate over it, but not afterwards), so IMO that's best used when it needs to be a generator, for semantics or performance.
You could turn it into a generator, then add a wrapper that turns it into a list (keeping the inner function private), or use a decorator that does the same, but it's less clear than this pattern.
So, i'd just learn to live with it.
- CogitoCogito 3y agoYeah I think using a list comprehension is overkill. The main reason I like list comprehensions is because I don't introduce variables (even temporarily) that I don't really need. I think that clarifies the code. But putting the code in a separate function also avoids introducing those variables to the current scope only at a cost of putting the code somewhere else (which I personally think has a cost). In this case I would just use a function or (probably) just inline it as you don't like.
- tomn 3y ago> which I personally think has a cost Yeah, so many people don't get this, but too many small functions can be hard to understand -- that's why I qualified that option. In this case i agree that inlining it is fine, i was talking about the general pattern.