Conditional iteration
at
at at tuko.nl
Thu Dec 14 13:03:16 EST 2006
Dear Duncan,
Points taken. Its just a workaround for a specific case, I know. Maybe I
just love the elegance of
new_list = [x for x in some_list if some_cond]
and like to see it extended...
I got I nice tip on generators however which would allow me to something
similar without consuming too much additional resources.
Kind regards,
Arjan
Duncan Booth wrote:
> at <at at tuko.nl> wrote:
>
>> By the way,
>>
>> I think by approving
>>
>> a = b if condition else c
>>
>> used to avloind
>>
>> if condition:
>> a = b
>> else:
>> a = c
>
> Neither of those is much of an improvement over the other, and in fact if
> b or c are complex expressions I would definitely favour the longhand
> form. The benefit of having a conditional expression though is that in
> some situations it can make the code clearer by allowing you to avoid
> creating a name at all. e.g. if 'a' was then used as a parameter in a
> function call:
>
> d = fn(b if condition else c)
>
> and a has disappeared entirely.
>
>>
>> which is dealing with same psychological problem, Guido also
>> recognizes some need...
>>
>> Is it redundant according to your criteria, yes I would say:
>>
>> a = {True: a, False: c}[condition]
>>
>> or
>>
>> a = [c, a][condition]
>>
>> would yield exactly the same even in one sentence....
>
> You do realise, I hope, that neither of these last two gives the same
> results as the inline 'if'?
>
>>>> x = 0
>>>> print 3/x if x != 0 else -1
> -1
>>>> print {True: 3/x, False: -1}[x != 0]
>
> Traceback (most recent call last):
> File "<pyshell#2>", line 1, in <module>
> print {True: 3/x, False: -1}[x != 0]
> ZeroDivisionError: integer division or modulo by zero
>>>> print [-1, 3/x][x != 0]
>
> Traceback (most recent call last):
> File "<pyshell#3>", line 1, in <module>
> print [-1, 3/x][x != 0]
> ZeroDivisionError: integer division or modulo by zero
>>>>
>
> and before you suggest the good old standby and/or technique, that fails
> for other values:
>
>>>> print x != 0 and 3/x or -1
> -1
>>>> x=5
>>>> print x != 0 and 3/x or -1
> -1
>>>>
>
> You need to use the messy:
>
>>>> print (x != 0 and (3/x,) or (-1,))[0]
> 0
>
> to get exactly the same effect as the inline if with loss of both
> readability and performance.
More information about the Python-list
mailing list