Pylint prefers list comprehension over filter...

Chris Angelico rosuav at gmail.com
Thu May 5 21:33:39 EDT 2016


On Fri, May 6, 2016 at 11:26 AM, Christopher Reimer
<christopher_reimer at icloud.com> wrote:
> Below is the code that I mentioned in an earlier thread.
>
>     string = "Whiskey Tango Foxtrot"
>     ''.join(list(filter(str.isupper, string)))
>
>     'WTF'
>
> That works fine and dandy. Except Pylint doesn't like it. According to this
> link, list comprehensions have replaced filters and the Pylint warning can
> be disabled.
>
> http://stackoverflow.com/questions/3569134/why-doesnt-pylint-like-built-in-functions
>
> Here's the replacement code using list comprehension:
>
>     ''.join([x for x in string if x.isupper()])
>
> Which is one is correct (Pythonic)? Or does it matter?

Nothing wrong with filter. Since join() is going to iterate over its
argument anyway, you don't need the list() call, you can remove that,
but you don't have to go for comprehensions:

''.join(filter(str.isupper, string))

Rule of thumb: If the function already exists, use filter or map. If
you would be using filter/map with a lambda function, reach for a
comprehension instead.

In this case, str.isupper exists, so use it!

ChrisA



More information about the Python-list mailing list