darksaga
darksaga

Reputation: 2186

Efficient list comparison in python

I'd like to efficiently compare two lists and determine if both share exactly the same elements.

The lists can be None, empty and of various lengths. Ordering of the elements inside the list does not matter, so ['a', 'b', 'c'] == ['a', 'c', 'b'] are equal in my case.

My current solution looks like this:

 def list_a_equals_list_b(list_a, list_b):
    if list_a != None and list_b != None:
        if len(list_a) != len(list_b):
            return False
        else:
            return len(frozenset(list_a).intersection(list_b)) == len(list_a)
    elif list_a == None and list_b == None:
        return True
    else:
        return False

Is there a more efficient way to compare those lists?

Thanks!

Upvotes: 0

Views: 516

Answers (2)

Alain T.
Alain T.

Reputation: 42143

If you don't have duplicates in either lists you can use a set:

if listA == listB  \
or listA and listB \
   and len(listA) == len(listB) \
   and not set(listA).symmetric_difference(listB):
   # lists have the same elements
else:
   # there are differences

If you do allow duplicates, then yo can use Counter from collections (which would also work if you don't have duplicates)

from collections import Counter

if listA == listB  \
or listA and listB \
   and len(listA) == len(listB) \
   and Counter(listA)==Counter(listB):
   # lists have the same elements
else:
   # there are differences

Upvotes: 2

alim91
alim91

Reputation: 546

The Counter() method is best if your objects are hashable. but here sorted() built-in function is your best option.

def list_a_equals_list_b(list_a, list_b):
    return (list_a == None and list_b == None) or sorted(list_a) == sorted(list_b)

Upvotes: 1

Related Questions