1

Is there a preferred general solution for testing equality of a list of lists. I'm attempting the apply this example more generally to a list of lists. I currently have the following solution, where _list is a generic list of unknown length/number of elements.

all(x == y for x, y in zip(_list, _list[1:]))

or if the order doesn't matter.

all([sorted(x) == sorted(y) for x, y in zip(_list, _list[1:])])

Beyond checking neighbouring lists for equality, how can/should this approach my improved?

Josmoor98
  • 1,721
  • 10
  • 27
  • 2
    I believe you can skip the list creation and just do `all(x == y for x, y in zip(_list, _list[1:]))` – Dani Mesejo Feb 11 '19 at 13:06
  • 1
    Note that you do not have to compare each element with each other. You only need to check whether any, say the first, equals all others. – MisterMiyagi Feb 11 '19 at 13:07
  • Your question suggests you want to compare two different lists of lists, but your code compares one list of lists to itself. Which is it? – Useless Feb 11 '19 at 13:10
  • 1
    Moreover, slicing will copy the tail of the list which is unecessarily costly. – Olivier Melançon Feb 11 '19 at 13:10
  • 1
    You can hash the content of every list to a string, you will end up with a list of strings, then check `len(set(list_of_strings)) == 1` – Mohamed Ali JAMAOUI Feb 11 '19 at 13:12
  • one *terrible* way to do this is use [itertools.combinations](https://docs.python.org/3.6/library/itertools.html#itertools.combinations) – Nullman Feb 11 '19 at 13:17

2 Answers2

2

I believe, simple and fast enough way would be

all(a[0] == ax for ax in a)

You don't need to compare all elements pairwise, short route is to compare 1 vs all others. And in reality, better to compare against all (ax in a) instead of "against others" (ax in a[1:]), as slicing is most probably more computation-intensive that single comparison. Depends on your data, tho, but in general I'd suggest not bothering.

Slam
  • 8,112
  • 1
  • 36
  • 44
-2

use sorted build in function: for example if you have two list x and y then compare like: sorted(x)==sorted(y)

list1 = [7,9,8]
list2 = [8,7,9]
sorted(list1)==sorted(list2)
Pradeep Pandey
  • 307
  • 2
  • 7