Split a list into two parts based on a filter?
Jussi Piitulainen
jpiitula at ling.helsinki.fi
Wed Jun 12 08:06:36 EDT 2013
Roy Smith writes:
> We've been in the twilight zone for a while. That's when the fun
> 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.
I expect e(s) in [e(s) for s in songs] to be an expression that is
evaluated for its value and not for an effect. The comprehension
should stand for a list of those values. The one above violates this
expectation.
> 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)
>
> or even:
>
> for s in songs:
> the_right_list = new_songs if s.is_new() else old_songs
> the_right_list.append(s)
These are fine.
More information about the Python-list
mailing list