user1254962
user1254962

Reputation: 153

extra empty element when removing an element from a tuple

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

Answers (2)

leafduo
leafduo

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

Ashwini Chaudhary
Ashwini Chaudhary

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

Related Questions