Reputation: 21
I got 2 lists:
alist = ['A','B','C','D']
anotherList = ['A','C','B','D']
would like to write a function which returns True
if both lists contain the exact same elements, and are same length. I'm kinda new on this stuff, so I got this, which I'm pretty sure it's terrible, and I'm trying to find a more efficient way. Thanks!
def smyFunction(aList,anotherList):
n = 0
for element in aList:
if element in anotherList:
n = n+1
if n == len(aList):
return True
else:
return False
Upvotes: 0
Views: 1841
Reputation:
Sort the lists with sorted
and then compare them with ==
:
>>> alist = ['A','B','C','D']
>>> anotherList = ['A','C','B','D']
>>> def smyFunction(aList,anotherList):
... return sorted(aList) == sorted(anotherList)
...
>>> smyFunction(alist, anotherList)
True
>>>
You need to sort them first in case the elements are out of order:
>>> alist = ['A','B','C','D']
>>> anotherList = ['D','A','C','B']
>>> alist == anotherList
False
>>> sorted(alist) == sorted(anotherList)
True
>>>
Actually, it would probably be better to test the length of the lists first and then use sorted
:
return len(alist) == len(anotherList) and sorted(alist) == sorted(anotherList)
That way, we can avoid the sorting operations if the lengths of the list are different to begin with (using len
on a list has O(1)
(constant) complexity, so it is very cheap).
Upvotes: 1
Reputation: 96258
If there aren't duplicates, use a set
, it doesn't have an order:
set(alist) == set(anotherList)
Upvotes: 0
Reputation: 117856
The two ways that come to mind are:
1) Use collections.Counter
>>> from collections import Counter
>>> Counter(alist) == Counter(anotherList)
True
2) Compare the sorted lists
>>> sorted(alist) == sorted(anotherList)
True
Upvotes: 4