Fix Python – How can I compare two ordered lists in python?

Question

Asked By – Jeremy

If I have one long list: myList = [0,2,1,0,2,1] that I split into two lists:

a = [0,2,1]
b = [0,2,1]

how can I compare these two lists to see if they are both equal/identical, with the constraint that they have to be in the same order?

I have seen questions asking to compare two lists by sorting them, but in my specific case, I am not checking for a sorted comparison, but identical list comparison.

Now we will see solution for issue: How can I compare two ordered lists in python?


Answer

Just use the classic == operator:

>>> [0,1,2] == [0,1,2]
True
>>> [0,1,2] == [0,2,1]
False
>>> [0,1] == [0,1,2]
False

Lists are equal if elements at the same index are equal. Ordering is taken into account then.

This question is answered By – Maxime Lorant

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0