On Wed, 21 Feb 2007, Dick Moores 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 nothing special; it's just a lookup in a list. First, there's a list of strings; the two strings are an empty string '' and a minus sign '-'. That's this part: ['','-'] If n is less than zero, I want to pick up the minus sign; otherwise, I want to pick up the empty string. The expression n<0 evaluates to the boolean True for the first case, and False otherwise. When using a boolean as an index in a list, True is treated as 1; False is treated as 0. This is the only arguably tricky part, if you've never played with booleans; it's documented at http://docs.python.org/ref/types.html: "Boolean values [False and True] behave like the values 0 and 1, respectively, in almost all contexts...". That's this part: [n<0] So: sign = ['','-'][n<0] is more or less the equivalent of: signlist = ['','-'] if n < 0: sign = signlist[1] else: sign = signlist[0] _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor