163

I have 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.

3 Answers 3

263

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This can return the following error with a numpy list: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
What @AlexReynolds said. You have to test with all(arr1 == arr2) or (arr1 == arr2).all().
@Alex That's an array, not a list. They're both ordered data types, but conceptually different. An action you apply to an array is applied to all of its elements, but the same isn't true for lists.
14

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.

1 Comment

And then check whether c.all() is True
6

The expression a == b should do the job.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.