Steve D'Aprano <steve+pyt...@pearwood.info> writes:

> Every few years, the following syntax comes up for discussion, with some 
> people
> saying it isn't obvious what it would do, and others disagreeing and saying
> that it is obvious. So I thought I'd do an informal survey.
>
> What would you expect this syntax to return?
>
> [x + 1 for x in (0, 1, 2, 999, 3, 4) while x < 5]
>
> For comparison, what would you expect this to return? (Without actually trying
> it, thank you.)
>
> [x + 1 for x in (0, 1, 2, 999, 3, 4) if x < 5]

These are not unclear (I think I'd guess that same as most people) but
adding a new while clause, and the existing if clause, both seem to be
rather narrow solutions.  The general solution would be to filter the
iterable (if that's the right term for it).  In Haskell:

  [x+1 | x <- takeWhile (<5) [0, 1, 2, 999, 3, 4]]
  [x+1 | x <- filter    (<5) [0, 1, 2, 999, 3, 4]]

I am sure you can already do this in Python but presumably it's not
convenient or there would be little incentive to build "takeWhile" into
the language.

<snip>
-- 
Ben.
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to