Armageddon80 Armageddon80 - 28 days ago 8
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

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'
else:
  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.