3 ms·
> E.g. this reads easier for me: len([x for x in xs if x > 10]) At the expense of allocating a new list, maybe. But the `sum` convention is faster, space-effic
by Veedrac 11y ago
> E.g. this reads easier for me: len([x for x in xs if x > 10])
At the expense of allocating a new list, maybe. But the `sum` convention is faster, space-efficient and cleaner. It's also pretty obvious once you've seen it.
- crdoconnor 11y agoOk with generators then... I'm sure some people will look at this and think that it's summing all of the numbers over 10 in xs: sum(x > 10 for x in xs) Whereas with this, which is explicit, it's substantially less likely they'll think that: sum(1 for x in xs if x > 10) Again, I don't see the point of maintaining the weakened type system for a few minor 'clever' barely-short cuts like this. Look at what that kind of thinking did to perl. If python started throwing exceptions on all the code that treated True and False as integers, I'm pretty sure all the fixes done to accommodate that would probably make the code cleaner and easier to understand.
- Veedrac 11y ago> I'm sure some people will look at this and think that it's summing all of the numbers over 10 in xs Perhaps it's just a bias of familiarity, but that argument seems contrived to me. I'm worried the rest of my arguments will amount to "I like what I know", so perhaps we should lay this to rest as a difference in tastes. It does remind me a little of concatenation with `+`, which is oft-hated... and yet I've not seen a single error caused by it.
- cma 11y agoHow about this: sum(int(x > 10) for x in xs) Just require the conversion to be explicit.