Armageddon80 Armageddon80 - 9 months ago 44
Python Question

How do you compare the order of two lists that contain the same elements?

I am trying to determine if a list is sorted the same way as another list containing the same elements. For example:

a = ['a', 'b', 'c']
b = ['b', 'c', 'a']

if a != b:
print("Wrong order")

I want to be able to determine whether two lists have got the same ordering. It does not matter whether it is slightly different or completely, I just need to be able to tell if they are different.

omz omz
Answer Source

You could simply compare sorted versions of the lists:

if a == b:
  print 'Same elements, same order'
elif sorted(a) == sorted(b):
  print 'Same lists, different order'
  print 'Completely differeent'

There are of course more efficient ways to do this (e.g. you could check the lengths of the lists first...), but this is very readable.