Conditional operator in Python?
Michael Hudson
mwh21 at cam.ac.uk
Sun Apr 1 08:58:35 EDT 2001
qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) writes:
> Sat, 31 Mar 2001 21:22:54 -0800, Erik Max Francis <max at alcyone.com> pisze:
>
> > The Python FAQ, for instance, suggests x ? a : b can be reliably
> > substituted with
> >
> > (x and [a] or [b])[0]
>
> It computes both a and b.
No it doesn't:
/>> def f():
|.. print 1
|.. return 1
\__
/>> def g():
|.. print 2
|.. return 2
\__
->> (0 and [f()] or [g()])[0]
2
2
->> (1 and [f()] or [g()])[0]
1
1
> A correct solution is
> (0 and (lambda: a) or (lambda: b))()
This also works.
> Yes, it is ugly.
This is also true.
Cheers,
M.
--
. <- the point your article -> .
|------------------------- a long way ------------------------|
-- Cristophe Rhodes, ucam.chat
More information about the Python-list
mailing list