Why is () is ()
true, yet (0,) is (0,)
is false?
I thought they would be the same object. However, I'm apparently missing something.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets.
There is a difference in python tuple vs list and the syntax for both tuple and the list also differs such as, the items in tuples are surrounded by parentheses( ) and the items in lists are surrounded by square brackets [ ]. The list consumes more storage space than the tuples.
List and Tuple in Python are the classes of Python Data Structures. The list is dynamic, whereas the tuple has static characteristics. This means that lists can be modified whereas tuples cannot be modified, the tuple is faster than the list because of static in nature.
The primary difference between tuples and lists is that tuples are immutable as opposed to lists which are mutable. Therefore, it is possible to change a list but not a tuple. The contents of a tuple cannot change once they have been created in Python due to the immutability of tuples.
is
tests to see if both sides of the statement share the same memory address. It's basically a shorthand for id(a) == id(b)
>>> print id(()), id(())
30085168 30085168
>>> print id((0,)), id((0,))
38560624 38676432
>>>
As ()
happens fairly frequently, it is actually treated as a singleton by the Python Interpreter (just like integers from 0 to 255, empty strings, empty lists, etc.). When comparing (0, )
to (0, )
to the interpreter they are actually different variables in memory. If they were mutable, you could modify the first, and the second wouldn't change, hence they are not the same (a is not b
).
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