Ternary operator and tuple unpacking -- What am I missing ?
Tim Roberts
timr at probo.com
Tue Jan 13 02:29:43 EST 2009
imageguy <imageguy1206 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.
>
>Any chance someone could enlighten me on the rules for tuple unpacking
>as this seems inconsistent.
It's not the tuple unpacking that's burning you. It's simple operator
precedence.
>7) >>> c,d = n if n is not None else 0,0
>8) >>> print c,d
>9) (22, 11) 0
>10) >>> c,d = n if n is not None else (0,0)
>11) >>> print c,d
>12) 22 11
As line 10 makes clear, line 7 is interpreted thus:
c,d = (n if n is not None else 0) , 0
"c" gets bound to the result of the ternary (the tuple (22,11)), and "d"
gets bound to 0.
--
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the Python-list
mailing list