0

I have two lists say list1 = [1,2,3,4,5] and list2 = [1,2,3,4,5]. If I do list1 == list2, it will return True. Suppose, I have one more list, say, list3 = [5, 4, 3, 2, 1] and if now I do list1 == list3, it will return False.

Can anyone please explain what is happening behind the scene? Are we comparing the values or references?

Hemant
  • 619
  • 2
  • 6
  • 17
  • It does an ordered, element by element comparison, so obviously `[1, 2]` cannot equal `[2, 1]`. If you want unordered comparison, use sets. – ekhumoro Sep 29 '15 at 11:48
  • The [accepted answer to the tuple question](http://stackoverflow.com/a/5292332/2932052) includes also **a section about list comparison**. – Wolf Sep 29 '15 at 11:49
  • But there are also **differences**: `print [1,2]<[3], (1,2)<(3), (1,2)<(3,)` – Wolf Sep 29 '15 at 14:41

1 Answers1

1

You're comparing each element, in the same order they appear in the list. What's happening behind the scene is something like:

if len(a) != len(b):
    return False
for i in range(len(a)):
    if a[i] != b[i]:
         return False          
return True
Maroun
  • 94,125
  • 30
  • 188
  • 241