Split a list into two parts based on a filter?
Terry Reedy
tjreedy at udel.edu
Wed Jun 12 14:07:49 EDT 2013
On 6/12/2013 7:39 AM, Roy Smith wrote:
> starts. But, somewhat more seriously, I wonder what, exactly, it is
> that freaks people out about:
>
>>>>> [(new_songs if s.is_new() else old_songs).append(s) for s in songs]
>
> Clearly, it's not the fact that it build and immediately discards a
> list, because that concern is addressed with the generator hack, and I
> think everybody (myself included) agrees that's just horrible.
It is an example of comprehension abuse. Comprehensions express and
condense a stylized pattern of creating collections from another
collection or collections, possibly filtered. They were not mean to
replace for statements and turn Python into an fp languages. Indeed,
they do replace and expand upon the fp map function. Python for loops
are not evil.
> Or, is it the use of the conditional to create the target for append()?
> Would people be as horrified if I wrote:
>
> for s in songs:
> (new_songs if s.is_new() else old_songs).append(s)
No. That succinctly expresses and implements the idea 'append each song
to one of two lists.
> or even:
>
> for s in songs:
> the_right_list = new_songs if s.is_new() else old_songs
> the_right_list.append(s)
>
--
Terry Jan Reedy
More information about the Python-list
mailing list