3 ms·
For the evens_only implementation, is there a reason to use map/filter vs a generator? eg: evens_only = lambda nums: [n/2 for n in nums if n%2==0] seems to
by nmb 16y ago
For the evens_only implementation, is there a reason to use map/filter vs a generator? eg:
evens_only = lambda nums: [n/2 for n in nums if n%2==0]
seems to work just as well.
- l0nwlf 16y agoI think that is List Comprehension and not Generator. 'Return' would be replaced by 'Yield' in case of a generator.
- deleted 16y ago[deleted]
- gurraman 16y agoYou can use parens instead of brackets to create a generator (generator expression). (for x in y) Edit: in the case of lambdas I'm fairly sure that you can omit the parens as well as they are implicit. I'd still write them out though. Can't test as I'm on my ipad.
- drdaeman 16y agoWith [...] you are doing the same as list(...), so your example would return a list: >>> evens_only([1,2,3,4,5]) [1, 2] If you want a generator instead: evens_only = lambda nums: (n/2 for n in nums if n%2==0) So you'll get: >>> evens_only([1,2,3,4,5]) <generator object <genexpr> at 0x7f2ef79eaa00> I don't know which one would be more Pythonic, clean and simple lambda one-liner or two-lined simple function.