Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #108206

Re: Pylint prefers list comprehension over filter...

From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Subject Re: Pylint prefers list comprehension over filter...
Date 2016-05-06 11:33 +1000
Message-ID <mailman.421.1462498422.32212.python-list@python.org> (permalink)
References <572BF2BF.6000000@icloud.com> <CAPTjJmp96gew0igPzVj-pa1aV1CzcAUeTtdqnhJTKV1sqUyT-g@mail.gmail.com>

Show all headers | View raw


On Fri, May 6, 2016 at 11:26 AM, Christopher Reimer
<christopher_reimer@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Pylint prefers list comprehension over filter... Chris Angelico <rosuav@gmail.com> - 2016-05-06 11:33 +1000

csiph-web