Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare object to empty tuple with the 'is' operator in Python 2.x

Tags:

python

I'm used to seeing if obj is None: in Python, and I've recently come across if obj is ():. Since tuples are not mutable, it sounds like a reasonable internal optimization in the Python interpreter to have the empty tuple be a singleton, therefore allowing the use of is rather than requiring ==. But is this guaranteed somewhere? Since which version of the interpreter?

[edit] the question matters because if () is not a singleton and there is a way of producing an empty tuple with a different address, then using is {} is a bug. If it is only guaranteed since Python 2.x with x > 0, then it is important to know the value of x if you need to ensure backward compatibility of your code. It is also important to know if this can break your code when using pypy / jython / ironpython...

like image 828
gurney alex Avatar asked Nov 18 '11 16:11

gurney alex


People also ask

How do you know if a tuple is empty?

Check if Tuple is Empty len() builtin function, with the tuple as argument, returns length of the tuple. If the length is zero, then then tuple is empty.

How do you represent an empty tuple in Python?

There are two ways to initialize an empty tuple. You can initialize an empty tuple by having () with no values in them. You can also initialize an empty tuple by using the tuple function. A tuple with values can be initialized by making a sequence of values separated by commas.

Can we compare 2 tuples in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.


1 Answers

From the Python 2 docs and Python 3 docs:

... two occurrences of the empty tuple may or may not yield the same object.

In other words, you can't count on () is () to evaluate as true.

like image 59
Steven Rumbalski Avatar answered Oct 06 '22 21:10

Steven Rumbalski