Reputation: 153
I have a question about the following python outcome. Suppose I have a tuple :
a = ( (1,1), (2,2), (3,3) )
I want to remove (2,2)
, and I'm doing this with the following code:
tuple([x for x in a if x != (2,2)])
This works fine, the result is: ( (1,1), (3,3) )
, just as I expect.
But suppose I start from a = ( (1,1), (2,2) )
and use the same tuple() command, the result is ( (1,1), )
while I would expect it to be ((1,1))
In short
>>> a = ( (1,1), (2,2), (3,3) )
>>> tuple([x for x in a if x != (2,2)])
((1, 1), (3, 3))
>>> a = ( (1,1), (2,2) )
>>> tuple([x for x in a if x != (2,2)])
((1, 1),)
Why the comma and empty element in the second case? And how do I get rid of it?
Thanks!
Upvotes: 3
Views: 2983
Reputation: 144
It indicates a one-element tuple, just to prevent confusion.
(1,)
is a tuple, while (1)
is just the number 1 with unnecessary parentheses.
Upvotes: 0
Reputation: 250961
Python uses a trailing comma in case a tuple has only one element:
In [21]: type((1,))
Out[21]: tuple
from the docs:
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
Upvotes: 6