2 ms·
You can omit == 0 in Python because 0 is falsy like in C and add a not after the if. That gains another character sum(x * x for x in [1,2,3,4] if not x % 2)
by pmontra 10y ago
You can omit == 0 in Python because 0 is falsy like in C and add a not after the if. That gains another character
sum(x * x for x in [1,2,3,4] if not x % 2)
and it matches this Ruby 2.4.0 (which added Array#sum)
[1,2,3,4].map{|x| x.even? ? x * x : 0}.sum
You understood correctly that the point was not sheer compactness. I only wanted to provide a context to judge the Module.function syntax compared to the object.method one. The filter, map, reduce example was accidental and I'm sure there are clever ways to compact that example further in both languages.
So the pythonic way is be
reduce_function(map_function(x) for x in input if filter_condition)
I prefer to write it in the order it runs (filter -> map -> reduce) but that's it. Thanks.