[Tutor] Function for converting ints from base10 to base2?
Jerry Hill
malaclypse2 at gmail.com
Thu Feb 22 03:44:21 CET 2007
On 2/21/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.
['', '-'] is a list with two elements: an empty string, and the string '-'.
[n<0] is an index into the list.
For example:
>>> a = ['First Element', 'Second Element']
>>> a[False]
'First Element'
>>> a[True]
'Second Element'
This works because int(True) is 1 and int(False) is 0. Personally, I
find using boolean values to index a list to be hard to read. If I
ever came back to looking at the code again, I'd rather have written
something like this:
sign = ''
if (n < 0): sign = '-'
It's an extra line of code, but it's a lot less cryptic to me.
--
Jerry
More information about the Tutor
mailing list