Say I have a list of strings, and I want to filter out all non-upper case strings. Is there a simpler way than doing filter(lambda x: x.isupper(), list)?
2 Answers
While I would prefer a list comprehension, this seems to be what you're looking for:
filter(str.isupper, list)
3 Comments
Jess
If the function already works as-is, why bother with the comprehension?
Cosmologicon
You're right, this is a perfectly fine use of filter. I hardly ever use it is all. I just like comprehensions.
senderle
Clearly you're using
list as a metasyntactic variable here, but if you weren't, I would have to point out that using list this way masks a built-in ;).uppers = [s for s in list if s.isupper()]
3 Comments
Steven Rumbalski
I think this would be easier to read with
s as the variable name instead of i.CromTheDestroyer
I'm sorry, I should have clarified that the question was about passing methods into functions as functions, not solving this trivial problem.
manji
ok, no problem. (if you re-read your question you will see that it's nearly impossible to understand that).
lambdais as much boilerplate as the wordfilter. Only in the most trivial of cases could is be considered "boilerplate".lambda x: x.isupper() and x not in ('Z','z')would demonstrate that thelambdais essential syntax.