Custom Search

Sunday, April 17, 2011

python Conditional Assignment trick

x = 3 if (y == 1) else 2

Assign 3 to x if y is 1, otherwise assign 2 to x.
Note that the parens are not necessary, but I
like them for readability. You can also chain it if
you have something more complicated:

x = 3 if (y == 1) else 2 if (y == -1) else 1

No comments:

Post a Comment