Another newbie question

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Fri Dec 9 02:10:08 CET 2005

```solaris_1234 at yahoo.com a écrit :
>
> I'm off to study the code. (Hmm.. how does python parse ("green",
> "red")[(i * 8 + j) % 2]  command ...

("green", "red")[0] == "green"
("green", "red")[1] == "red"

(i * 8 + j) is somewhat trivial (just take care of precedence order),
and will return an integer
% is the modulo operator.
the modulo 2 of any integer x is 0 if x is even and 1 if x is odd
(that's in fact the reversed definition !-)

So this expression[1] will return "green" if (i * 8 + j) is pair and
"red" if (i * 8 + j) is even.

Using computed indexed access for dispatch is a common python idiom.

if condition:
result = iftrue
else:
result = iffalse

you can simply write:
result = (iffalse, iftrue)[condition]

[1] 'expression', not 'command'. An expression has a value and can be
used on the right hand side of the assignment operator.

> he says while reaching for "python
> for the semi-illiterate"  ...)
>

```