On 22/02/07, Dick Moores <[EMAIL PROTECTED]> wrote:
> But there's syntax(?) there I've never seen before. "['','-'][n<0]".
> I see it works:
>
>  >>> n = -6
>  >>> ['','-'][n<0]
> '-'
>  >>> n = 98
>  >>> ['','-'][n<0]
> ''
>
> What's this called? I'd like to look it up.

It's taking advantage of the fact that booleans (True, False) are integers.

>>> 1 == True
True
>>> 0 == False
True
>>> ['zero', 'one'][True]
'one'

It's more compact, but less clear (IMO), so I'm not a big fan.

Hmm, and it may not be faster either:

Morpork:~ repton$ python -m timeit -s 'n=13' 'x=["", "-"][n<0]'
1000000 loops, best of 3: 0.6 usec per loop
Morpork:~ repton$ python -m timeit -s 'n=13' 'if n < 0:' ' x="-"'
'else:' ' x=""'
1000000 loops, best of 3: 0.251 usec per loop

-- 
John.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to