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...
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With