0

Why am I getting a strange 0 2 result when I give this to Python?

#tuples ~wtF?
a=()
b=(a)
c=(a,1)
len(b)
len(c)

NB: I get an expected 1 2 result for lists:

a=[]
b=[a]
c=[a,1]
len(b)
len(c)

This is happening on Linux:

$ python --version
Python 2.7.2+

Edit: wrt answers so far

So is this somehow because of the , in the c=(a,1) assignment?

>>> print b
()
>>> print c
((), 1)

2 Answers 2

7

The brackets don't make it a tuple - the comma does. Consider:

>>> 5 * (3 + 2)
25

The brackets there mean 'do this first'. The brackets in:

b=(a)

Mean the same. So, this is equivalent to

b = a 

so b is a will be True.

To make b a tuple containing the empty tuple, you need to do:

b = a, 

Again, the brackets don't make it a tuple (except for the special case of () is the empty tuple), the comma does.

For the edit,

c = (a, 1)

Since a = (), this is the same as:

c = ((), 1)

ie, it is a tuple containing the empty tuple and 1. () is always the empty tuple (same as [] is the empty list), but this it the only time the brackets mean 'tuple'. The above is the same as:

c = (), 1

Though normally people do include the brackets here (and the repr and str of tuples always do), this is for style rather than because they're meaningful.

1
  • 9000 beat you to it but i give you a +1 anyhows =)
    – violet313
    Jun 8, 2012 at 2:40
5

(a) is just an expression a, like (1+2) is just 1+2.

If you want 1-item tuple, you write (a,). BTW same syntax works with lists: [a,]. And with function argument lists, too. Trailing comma is acceptable everywhere where a comma-separates list is.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.