When comparing a tuple with a list like ...
>>> [1,2,3] == (1,2,3) False >>> [1,2,3].__eq__((1,2,3)) NotImplemented >>> (1,2,3).__eq__([1,2,3]) NotImplemented
... Python does not deep-compare them as done with (1,2,3) == (1,2,3)
.
So what is the reason for this? Is it because the mutable list can be changed at any time (thread-safety issues) or what?
(I know where this is implemented in CPython, so please don't answer where, but why it is implemented.)
Python tuples vs lists – Mutability. The major difference between tuples and lists is that a list is mutable, whereas a tuple is immutable. This means that a list can be changed, but a tuple cannot.
One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.
Lists are mutable while tuples are immutable, and this marks the key difference between the two. What does this mean? We can change/modify the values of a list but we cannot change/modify the values of a tuple. Since lists are mutable, we can't use a list as a key in a dictionary.
The advantages of tuples over the lists are as follows: Tuples are faster than lists. Tuples make the code safe from any accidental modification. If a data is needed in a program which is not supposed to be changed, then it is better to put it in 'tuples' than in 'list'.
You can always "cast" it
>>> tuple([1, 2]) == (1, 2) True
Keep in mind that Python, unlike for example Javascript, is strongly typed, and some (most?) of us prefer it that way.
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