5 ms·
What's the advantage of list comprehension over lambdas (assuming the lambda syntax is decently lightweight)? I feel like I come down hard on the side of lambd
by akavi 10y ago
What's the advantage of list comprehension over lambdas (assuming the lambda syntax is decently lightweight)?
I feel like I come down hard on the side of lambdas, but I've never really spent enough time in a language with list comprehension, so there's a good chance I'm missing something.
- brianwawok 10y agoI think it's just less to type really, and it's considered the more standard way to do it.
- cwilkes 10y agoI find it a lot easier to read, part of which is that I'm used to the Scala way of sequence dot map function. When I see the python one I can't remember if the function comes first or the array.
- warbiscuit 10y agoI'm not positive, but I think it saves the need to create a new execution frame for each lambda call, since the whole loop executes in single frame used by the comprehension. In theory I suppose the VM could have a map() implementation which opportunistically extracts the code from a lambda and inlines them when possible; but doubt CPython does that. OTOH, I'd be surprised if PyPy doesn't do something like that.
- fovc 10y agoSince Python 3, both generators and lists create a new stack frame. [1] (2nd to last paragraph) [1] http://python-history.blogspot.com/2010/06/from-list-comprehensions-to-generator.html http://python-history.blogspot.com/2010/06/from-list-compreh...
- warbiscuit 10y agoI'm not meaning when the comprehension is invoked, but during each iteration of the loop within the comprehension. When doing something like `map(lambda x: 2+x, range(100))`, there will be 101 frames created: the outer frame, and 100 for each invocation of the lambda. Whereas `[2+x for x in range(100)]` will only create 2: one for the outer frame, and one for the comprehension.
- quietwhisper 10y agohow can you come down hard on the side of one when you've never experienced the other? I'm from a non-list-comprehension background too, but recently started working a lot in a large python codebase, and have found the dict/list comprehensions to be beautiful. I'm a huge fan. It's a shame lambda syntax is not the best and it's generally crippled, but comprehensions are a great 80/20 compromise for handling most cases very cleanly.