7 ms·
The pythonic (i.e. right) way to write this is: x = [i * 10 for i in [1, 2, 3]]
by lyschoening 10y ago
The pythonic (i.e. right) way to write this is:
x = [i * 10 for i in [1, 2, 3]]
- SeanDav 10y agoi. let x = [ 1, 2, 3].map(i => i * 10) ii. x = list(map((lambda i: i * 10), [ 1, 2, 3 ])) iii. x = [i * 10 for i in [1, 2, 3]] All these methods are really just multiple sides of the same coin. All I see is different syntax, none looks any better from my point of view and unless there is a clear performance benefit, just use what you are used to, or what your coding standards define.
- NegativeLatency 10y agoI think in general the comprehension is faster because of how method calls and symbol lookups work in python. For the most part it's just a style thing.
- lyschoening 10y agoii. vs iii. boils down to explicit rather than implicit. iii. is simply easier to understand. I believe most people would also agree that ii. doesn't look particularly nice.
- spraak 10y agoI understand superficially that this works, but can you explain the syntax (or is there a name for this)? So far I've also seen a for loop like for i in [1,2,3]: ...
- spraak 10y agoAnswer to my question: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions https://docs.python.org/2/tutorial/datastructures.html#list-...