3 ms·
Why not use map? spam = map (eggs, spam) Even shorter, more concise and clearer. What is not to like, as Seinfeld would say?
by ovi256 19y ago
Why not use map?
spam = map (eggs, spam)
Even shorter, more concise and clearer. What is not to like, as Seinfeld would say?
- scott_s 19y agoSometimes it is, sometimes it's not. If you allow me to generalize this to list comprehensions vs. standard functional techniques, sometimes the list comprehension is cleaner. Take the list comprehension [f for f in os.listdir('.') if f.endswith('.csv') and not f.endswith('_avg.csv')] The lambda alternative (which would make a great blog name) is filter(lambda f: f.endswith('.csv') and not f.endswith('_avg.csv'), os.listdir('.')) I find the list comprehension cleaner because it introduces less noise.
- avinashv 19y agoAgreed. > The lambda alternative (which would make a great blog name) I'm stealing that.
- inklesspen 19y agoDammit!
- avinashv 19y agoI mentioned it in the article: map was going to be deprecated in 3000, but now will return iterators. Contextually, not what you want.
- etal 19y agoPy3K goes wild with generators. Basically, everything that used to return a list (e.g. range()) now returns an iterable, and to get a list you just apply the list() constructor to that. It's about lazy evaluation. So these will be equivalent: dinner = [eggs(x) for x in spam] dinner = list(eggs(x) for x in spam) dinner = list(map(eggs, spam) The real reason list comprehensions are favored over map() and filter() are that the latter two require another Python function call, while list comprehensions are evaluated directly by the interpreter (a bit like rewriting the loop in C or using Pyrex) -- better performance.