Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why is comparison between lists and tuples not supported?

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.)

like image 920
AndiDog Avatar asked Feb 26 '10 21:02

AndiDog


People also ask

Can you compare tuples and lists in Python?

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.

Can we compare a list and tuple?

One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.

Why lists are mutable and tuples are not?

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.

What are three advantages that tuples have in comparison to lists?

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'.


1 Answers

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.

like image 82
Esteban Küber Avatar answered Sep 21 '22 11:09

Esteban Küber