Why the expression "(1)" is not an one-arity tuple, but int ?

Andre Engels andreengels at gmail.com
Fri Dec 4 07:26:13 EST 2009


2009/12/4 Петров Александр <gmdidro at gmail.com>:
> Hello All !
>
> In my code I try to use a generic approach to work with tuples. Let
> "X" be a tuple.
> When I want to access a first element of a tuple, I can write: "X[0]".
> And that is really working when X is a n-arity tuple, with n>1 (for
> example "foo( (1,2,3) )" ).
> But when I call my library function with a 1-arity tuple (for example
> "foo( (1) )" ) I have an error:
>
> TypeError: 'int' object is unsubscriptable
>
> How could I tell Python that "(1)" is not an integer, but an one-arity tuple ?

Tuples in Python are recognized/defined not by the brackets, but by
the commas; the brackets just function to specify the exact beginning
and ending of the tuple in cases where that is not directly clear.
"(1,2,3)" is a tuple, but "1,2,3" is also the same tuple. A 1-tuple
can be created as "1," or "(1,)".

-- 
André Engels, andreengels at gmail.com



More information about the Python-list mailing list