best way to compare contents of 2 lists?

Piet van Oostrum piet at cs.uu.nl
Fri Apr 24 09:43:22 CEST 2009


>>>>> John Yeung <gallium.arsenide at gmail.com> (JY) wrote:

>JY> It takes care of the duplicates, but so does your initial solution,
>JY> which I like best:

>>> sorted(a)==sorted(b)

>JY> This is concise, clear, and in my opinion, the most Pythonic.  It may
>JY> well even be the fastest.  (If you didn't have to match up the numbers
>JY> of duplicates, the set solution would be most Pythonic and probably
>JY> fastest.)

But it may fail if the list cannot be sorted because it contains
incomparable elements:

>>> a = [1, 2, 3+4j]
>>> b = [2, 3+4j, 1]
>>> set(a) == set(b)
True
>>> sorted(a)==sorted(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: no ordering relation is defined for complex numbers

In Python 3 there are even more incomparable objects pairs.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list