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)?
asked Jun 6, 2011 at 17:32
CromTheDestroyer
3,8163 gold badges22 silver badges26 bronze badges
2 Answers 2
While I would prefer a list comprehension, this seems to be what you're looking for:
filter(str.isupper, list)
answered Jun 6, 2011 at 17:38
Cosmologicon
2,1873 gold badges16 silver badges18 bronze badges
Sign up to request clarification or add additional context in comments.
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()]
answered Jun 6, 2011 at 17:35
manji
48k5 gold badges98 silver badges104 bronze badges
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).
lang-py
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.