[Python-ideas] while conditional in list comprehension ?? (original) (raw)
Steven D'Aprano steve at pearwood.info
Wed Jan 30 23:56:14 CET 2013
- Previous message: [Python-ideas] while conditional in list comprehension ??
- Next message: [Python-ideas] while conditional in list comprehension ??
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 31/01/13 05:05, Oscar Benjamin wrote:
On 30 January 2013 17:56, Yuriy Taraday<yorik.sar at gmail.com> wrote:
On Wed, Jan 30, 2013 at 1:46 PM, Wolfgang Maier <wolfgang.maier at biologie.uni-freiburg.de> wrote:
your condition is 'partial(lt,50)', but this is not met to begin with and results in an empty list at least for me. Have you two actually checked the output of the code or have you just timed it? Yeah. Shame on me. You're right. My belief in partial and operator module has been shaken. This is why I prefer this stop() idea to any of the takewhile() versions: regardless of performance it leads to clearer code, that can be understood more easily.
Funny you say that, clarity of code and ease of understanding is exactly why I dislike this stop() idea.
It does not work with list, dict or set comprehensions, only with generator expressions. So if you need a list, dict or set, you have to avoid the obvious list/dict/set comprehension.
It is fragile: it is easy enough to come up with examples of the above that appear to work:
[i for i in range(20) if i < 50 or stop()] # appears to work fine [i for i in range(20) if i < 10 or stop()] # breaks
It reads wrong for a Python boolean expression. Given an if clause:
if cond1() or cond2()you should expect that an element is generated if either cond1 or cond2 are true. When I see "if cond1() or stop()" I don't read it as "stop if not cond1()" but as a Python bool expression, "generate an element if cond1() gives a truthy value or if stop() gives a truthy value".
This "if cond or stop()" is a neat hack, but it's still a hack, and less readable and understandable than I expect from Python code.
-- Steven
- Previous message: [Python-ideas] while conditional in list comprehension ??
- Next message: [Python-ideas] while conditional in list comprehension ??
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]