[Tutor] Function for converting ints from base10 to base2?

John Fouhy john at fouhy.net
Thu Feb 22 03:33:17 CET 2007


On 22/02/07, Dick Moores <rdm at rcblue.com> 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.


More information about the Tutor mailing list