violet313
violet313

Reputation: 1932

Unexpected Python tuple behaviour

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)

Upvotes: 0

Views: 776

Answers (2)

lvc
lvc

Reputation: 35059

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.

Upvotes: 7

9000
9000

Reputation: 40884

(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.

Upvotes: 5

Related Questions