Split a list into two parts based on a filter?

Peter Otten __peter__ at web.de
Tue Jun 11 02:43:41 EDT 2013


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 ;)




More information about the Python-list mailing list