How to compare two lists in python and return that the second should have the same values ​​regardless of order?

a = [1, 2, 3, 4] b = [2, 4, 3, 1] c = [2, 3] 

When comparing a with b, you should return True : all elements in a represented in b , and all elements in b represented in a .

When comparing a with c should return False : a contains elements that do not exist on c .

What is the pythonic way to do this?

+7
source share
4 answers

Sort, then compare.

 sorted(a) == sorted(b) 
+12
source

Use kits or freezats.

 set_a = {1, 2, 3, 4} #python 2.7 or higher set literal, use the set(iter) syntax for older versions set_b = {2, 4, 4, 1} set_a == set_b set_a - set_b == set_b - set_a 

The biggest advantage of using sets over any list method is that it is very readable, you have not changed your original iterative image, it can work well even when it is huge, and b is tiny (checking if there is a and b is the same length at first is a good optimization if you expect this to happen often), and using the correct data structure for the job is pythonic.

+5
source

Use set s:

 In [4]: set(a) == set(b) Out[4]: True In [5]: set(a) == set(c) Out[5]: False 
+2
source

Turn them into sets:

 >>> set([1,2,3,4]) == set([2,4,3,1]) True >>> set([2, 3]) == set([1,2,3,4]) False 

If your lists contain duplicate elements, you will also have to compare their lengths. Sets duplicate duplicates.

+2
source

All Articles