On 25/05/13 04:53, Albert-Jan Roskam wrote:
Why do I need to use a trailing comma to create a singleton tuple? Without a comma it seems to mean "parenthesized single object", ie the parentheses are basically not there.
Because round brackets are also used for grouping. You can group any expression: z = (x+1)*y Even an expression consisting of a single element: z = (x+1)*(y) That might not be a sensible thing to do, but it's not worth special-casing the parser to reject parentheses in this case. Now bring in tuples. Tuples are created by the comma operator, NOT the parentheses: a = 23, 42, None creates a tuple. At least one comma is necessary to distinguish an element from a tuple of one element: a = 23 # a is the int 23 a = 23, # a is a one-item tuple containing 23 Sometimes you use round brackets to group the tuple item, either because you need to change the precedence: a = 23, (2, 4, 8), None groups the three elements 2, 4, 8 into a tuple, which in turn is in a tuple: print a => (23, (2, 4, 8), None) Or we use round brackets to make a tuple just because it looks better, and matches the display of them: a = (23, 42, None) print a => (23, 42, None) But make no mistake: it is the comma, not the brackets, that makes the tuple. So single-item tuples are not special. They just follow the rules for multiple-item tuples, except that you only have item. That does leave the question of how to specify an empty tuple. And that is special: a = () however it does match the display of empty tuples, and looks rather similar to empty lists [] and empty dicts {}. -- Steven _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor