best way to compare contents of 2 lists?

norseman norseman at hughes.net
Fri Apr 24 13:39:39 EDT 2009


Esmail wrote:
> What is the best way to compare the *contents* of two different
> lists regardless of their respective order? The lists will have
> the same number of items, and be of the same type.
> 
> E.g. a trivial example (my lists will be larger),
> 
> a=[1, 2, 3]
> 
> b=[2, 3, 1]
> 
> should yield true if a==b
> 
> I suppose I could sort them and then compare them. I.e.,
> 
> sorted(a)==sorted(b)
> 
> 
> I am wondering if there is a more efficient/preferred way to do so.
> 
> Thanks,
> Esmail
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
=========================================
Technically, ==  is reserved for identical, as in byte for byte same

->If sorted(listA) == sorted(listB):
->  etc....
Is the preferred.

While there are other ways, the ones I know of are much more computer 
intensive.

Things like:
   get (next) line from file1
   if checking it against each line of file2 yields a found
     loop
   else
     ...
are a real I/O killers.
Indexes are good but introduce a separate maintenance issue.


By the way - does original order of original files count?
If not, sorting AND KEEPING can speed up future things.

Of course each method has its time and place of use and Python has some 
well oiled list search and list maintain routines of its own. List 
comparisons are most accurate when using presorted ones. (Some things 
don't lend themselves to sorting very well. Like paragraphs, books, 
chapters, computer programs, manuals, etc... These need the searchers 
(equivalent to the Unix diff) for checking equivalence.)


HTH

Steve



More information about the Python-list mailing list