1

Assuming:

a = [(1,2,3),(4,5,6)]
b = [(4,5,6),(1,2,3)]

I want the following comparison to be True. Meaning position of tuple inside list doesn't matter.

a == b
ruh
  • 139
  • 3
  • 9

3 Answers3

2

Create a multiset - collections.Counter object in Python - from both lists and compare those:

>>> from collections import Counter
>>> a = [(1,2,3), (4,5,6)]
>>> b = [(4,5,6), (1,2,3)]
>>> Counter(a) == Counter(b)
True
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Looks like an overkill... Why not just sort the lists? – DYZ Jan 14 '18 at 21:00
  • What makes you think it's an overkill as compared to O(nlogn) sorting ? You can't tell except you time both. – Moses Koledoye Jan 14 '18 at 21:03
  • Interesting approach - I wonder what the performance of `Counter` is compared to a sort? My gut feeling is that it would be faster... – match Jan 14 '18 at 21:03
  • 1
    @DYZ Correct me if i'm wrong, but building the `Counter` should be `O(n)`, while sorting is `O(nlogn)` – Patrick Haugh Jan 14 '18 at 21:03
  • 1
    It runs 15 times slower on this example. Probably because of counter creation overhead. – DYZ Jan 14 '18 at 21:03
  • @DYZ The speed of sort for a list of tuples depends on how dissimilar the items in the tuples are, which is pretty subjective. – Moses Koledoye Jan 14 '18 at 21:05
  • @MosesKoledoye If the first element is different, then comparison takes time O(1) with respect to the tuple length. On the other hand, hashing for dictionary lookup is always O(N). So, who knows. – DYZ Jan 14 '18 at 21:07
  • 3
    [Here's a REPL](https://repl.it/@Haugh/MidnightblueTightKudu) I threw together to check (using bare ints, not tuples). As expected, there comes a point where `Counter` pulls ahead in speed, though not by much compared to `sorted`. – Patrick Haugh Jan 14 '18 at 21:17
2

Sort the lists, then compare them:

a = [(1,2,3),(4,5,6)]
b = [(4,5,6),(1,2,3)]
sorted(a)==sorted(b)
# True
DYZ
  • 55,249
  • 10
  • 64
  • 93
0

If you don't care about repetitions, use sets: set(a) == set(b)

Otherwise, sort them: sorted(a) == sorted(b)

match
  • 10,388
  • 3
  • 23
  • 41