How does Python compare 2 lists?

In JavaScript, if you try to compare 2 arrays like this:

let a = [1, 2, 3]
let b = [1, 2, 3]
a === b

It just doesn t work since they are reference types and you compare the memory adresses. But if you do a comparison like that in Python it works. Does anyone know how Python does this?

Because the Python comparison operators (like ==) compare the elements in the two lists item by item, they don’t just check what the (reference) value of the list itself is.

So it goes into each list and iterates through them and compares values for equality.

Hello, Osiris.

Something to remember: Python does not have the === operator, but it does have the is operator, which is similar. So, in Python: a is b would return false.

Basically, Python comes in-built with a lexicographical order for list comparison, as this avoids having to write your own function as you would in JavaScript.

1 Like

Ye when I meant a === b for JS I was pointing to a==b equivalent in Python. Even tho Python is a high lvl language like JS and people say that Python it s easier to understand, to me it looks more weird than JS sometimes. Maybe I got used too much to JS. Having both == and is it s quite useful and it looks like it allows writing code with less lines than you would in JS.

I like Python a lot, but I’m not a proponent of learning it as a first language. The syntax is very easy when you start out, but there is so much “magic” that happens behind the scenes that it makes the learning curve get even steeper when you try to get into complex topics.