Split a list into two parts based on a filter?

Fábio Santos fabiosantosart at gmail.com
Tue Jun 11 09:48:20 EDT 2013


On 11 Jun 2013 07:47, "Peter Otten" <__peter__ at web.de> wrote:
>
> Fábio Santos wrote:
>
> > On 10 Jun 2013 23:54, "Roel Schroeven" <roel at roelschroeven.net> wrote:
> >>
> >> You could do something like:
> >>
> >> new_songs, old_songs = [], []
> >> [(new_songs if s.is_new() else old_songs).append(s) for s in songs]
> >>
> >> But I'm not sure that that's any better than the long version.
> >
> > This is so beautiful!
>
> It makes me cringe.
>
> This code does spurious work to turn what is naturally written as a for
loop
> into a list comprehension that is thrown away immediately. I think I'd
even
> prefer this "gem"
>
> >>> evens = []
> >>> odds = [item for item in range(10) if item % 2 or evens.append(item)]
> >>> evens, odds
> ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])
>
> but if I have my way every side effect in a list comprehension should be
> punished with an extra hour of bug-hunting ;)
>

What I like so much about it is the .. if .. else .. Within the parenthesis
and the append() call outside these parenthesis.

I agree it would be best written as a for loop, to increase readability and
avoid confusion. I always expect list comprehensions to be used as
expressions, and its use as a (single-expression) statement is rather odd.

On 11 Jun 2013 07:52, "Jonas Geiregat" <jonas at geiregat.org> wrote:
> I must disagree , this is unreadable and in my honor opinion not Pythonic
at all.
> I've learned it's always better to be explicit then implicit, and this
snippet of code does a lot in an implicit way.
>

(Read above)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130611/37bc3a22/attachment.html>


More information about the Python-list mailing list