How can I compare two ordered lists in python?

Python

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

If you want to just check if they are identical or not, a == b should give you true / false with ordering taken into account.

In case you want to compare elements, you can use numpy for comparison

c = (numpy.array(a) == numpy.array(b))

Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.

Solution 3 - Python

The expression a == b should do the job.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremyView Question on Stackoverflow
Solution 1 - PythonMaxime LorantView Answer on Stackoverflow
Solution 2 - PythonVasanthView Answer on Stackoverflow
Solution 3 - PythonAbhiramView Answer on Stackoverflow