0

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
8
  • @The Communist Duck: why is boilerplate bad? It's not a big deal, but it is annoying. Commented Jun 6, 2011 at 17:34
  • You could define a function to do this, but it will still take one line to invoke it. Commented Jun 6, 2011 at 17:38
  • @CromTheDestroyer: What part is "boilerplate"? Can you be more specific on what you object to? Commented Jun 6, 2011 at 17:38
  • @S.Lott: the lambda is. In my head I was contrasting it to the case where a function is passed in. Cosmologicon's answer is what I was looking for. Commented Jun 6, 2011 at 17:41
  • @CromTheDestroyer: The lambda is as much boilerplate as the word filter. 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 the lambda is essential syntax. Commented Jun 6, 2011 at 18:55

2 Answers 2

10

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
Sign up to request clarification or add additional context in comments.

3 Comments

If the function already works as-is, why bother with the comprehension?
You're right, this is a perfectly fine use of filter. I hardly ever use it is all. I just like comprehensions.
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 ;).
5
uppers = [s for s in list if s.isupper()]
answered Jun 6, 2011 at 17:35

3 Comments

I think this would be easier to read with s as the variable name instead of i.
I'm sorry, I should have clarified that the question was about passing methods into functions as functions, not solving this trivial problem.
ok, no problem. (if you re-read your question you will see that it's nearly impossible to understand that).

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.