Ternary operator and tuple unpacking -- What am I missing ?

imageguy imageguy1206 at gmail.com
Tue Jan 13 21:43:27 CET 2009


On Jan 13, 1:01 am, Miles <semantic... at gmail.com> wrote:
> On Tue, Jan 13, 2009 at 12:02 AM, imageguy <imageguy1... at gmail.com> wrote:
> > Using py2.5.4 and entering the following lines in IDLE, I don't really
> > understand why I get the result shown in line 8.
>
> > Note the difference between lines 7 and 10 is that 'else' clause
> > result enclosed in brackets, however, in line 2, both the 'c,d'
> > variables are assign correctly without the brackets being required.
>
> > 1) >>> n = None
> > 2) >>> c,d = n if n is not None else 0,0
> > 3) >>> print c,d, type(c), type(d)
> > 4) 0 0 <type 'int'> <type 'int'>
>
> The ternary expression has higher precedence than the comma, so the
> actual effect of line 2 (and 8) is:
>
> >>> c, d = (n if n is not None else 0), 0
>
> Or written more explicitly:
>
> >>> c = n if n is not None else 0
> >>> d = 0
>
> So the only correct way to write the expression, for the result you
> want, is to use your line 10:
>
> > 10)  >>> c,d = n if n is not None else (0,0)
>
> But if you're struggling with the precedence issues, I'd recommend
> ditching ternary expressions altogether and using full conditional
> blocks.
>
> -Miles

Thanks.
Hadn't thought through the operator precedence and the affect of the
comma.
This was the first time I tried to use with tuples, so will be more
careful next time
or stick to control blocks.

g.




More information about the Python-list mailing list