list comprehension problem

Ben Finney ben+python at benfinney.id.au
Tue Nov 3 08:59:37 CET 2009


Paul Rudin <paul.nospam at rudin.co.uk> writes:

> Falcolas <garrickp at gmail.com> writes:
>
> > [s.strip() for s in hosts if s.strip()]
>
> There's something in me that rebels against seeing the same call
> twice.

Agreed. I'd probably use:

    >>> lines = ["foo", "   ", " bar ", "", "baz"]
    >>> [s for s in (s.strip() for s in lines) if s]
    ['foo', 'bar', 'baz']

-- 
 \      “[I]t is impossible for anyone to begin to learn that which he |
  `\                thinks he already knows.” —Epictetus, _Discourses_ |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list