Hello,
Why is the comma in tup1 = (1,); required for a single element tuple in python?
Thanks.Code:#tup1 = (1); tup1 = (1,); print "tup1[0]: ", tup1[0]
Hello,
Why is the comma in tup1 = (1,); required for a single element tuple in python?
Thanks.Code:#tup1 = (1); tup1 = (1,); print "tup1[0]: ", tup1[0]
Because otherwise it's ambiguous with the arithmetic expression (1), which is 1 with some extra parentheses.
LambdaGrok. | #ubuntu-programming on FreeNode
hmm...
CptPicard, Sorry I'm being a bit slow here. Say in a data structure like array in any programming language, you want to have only one value, you would just assign the value alone right ? Something like
How is it different in tuples?Code:#include <stdio.h> int main(void) { int a[] = {1}; printf("%d",a[0]); return 0; }
Go to the Python shell and type (1). What do you get? How could you tell the difference between the expression of a parenthesized 1 and a single-element tuple if the latter also looks like (1)? You couldn't, so you need to define the tuple as something else... for example (1,).
LambdaGrok. | #ubuntu-programming on FreeNode
Corollary: to unpack your "unuple" you need the same kind of dangling comma:
Otherwise:Code:>>> t = (1,) >>> e, = t >>> e 1
Code:>>> e = t >>> e (1,)
Warning: unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
And an interesting feature of the tuple syntax I had not thought of before: The tuple actually seems to be just the comma-separated list of things, not the parenthesis around it. So the tuple (1,2) can be written as just "1,2".
LambdaGrok. | #ubuntu-programming on FreeNode
Warning: unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
LambdaGrok. | #ubuntu-programming on FreeNode
I did that, I got
Code:>>> a = (1) >>> print a; 1 >>> b = (1,) >>> print b (1,)But isn't a "parenthesized 1" same as a single-element tuple. I'm assuming that a tuple is the same as an array in C except that "A tuple is an immutable list. A tuple can not be changed in any way once it is created.(from google)"How could you tell the difference between the expression of a parenthesized 1 and a single-element tuple if the latter also looks like (1)? You couldn't, so you need to define the tuple as something else... for example (1,).
As per my understanding, since I think that a "parenthesized 1" is same as a single-element tuple, I still haven't got it completely.
No.
Code:>>> print 1 == (1) True >>> print 1 == (1,) False >>> print (1,) == (1,) True >>> print (1) == (1,) FalseUsing the C analogy, 1 is an int and an arrary of one int is not an int, it is an array.I'm assuming that a tuple is the same as an array in C except that "A tuple is an immutable list.
Bookmarks