Proposal: [... for ... while cond(x)]

Eighty eightyx at gmail.com
Tue Aug 8 15:18:02 EDT 2006


Eighty wrote:
> I suggest a new extension of the list comprehension syntax:
>
> [x for x in xs while cond(x)]
>
> which would be equivalent to
>
> list(itertools.takewhile(cond, xs))
>
> + Since Python favors list comprehensions over map, filter, and reduce,
> this would be the preferred way to do this
> + "Takewhile operations" occur often, at least for me
> + I don't think it would break any existing syntax
>
> An analogous syntax for dropwhile would be nice, but I can't think of
> one.
>
> This is not a PEP because it's a very simple idea and probably not just
> anyone (read: me) can write and submit one. If there has been a PEP for
> this, I've missed it; if not, it would be nice if someone wrote one.
>
> Discuss.

So does no one have a comment on this? The one objection I can come up
with is that this would change the set builder notation semantics too
much, but since the iteration order in a list comprehension is already
well defined, I don't think that would be the case. However, for this
reason, it wouldn't fit in a dict comprehension, if that would ever be
made, perhaps making the syntax inconsistent?




More information about the Python-list mailing list