Stories. Questions. Different perspectives.
Browse WAURE
← Advice & Questions
Technology · Advice & Questions ·

Why does Python say two identical-looking lists are not the same object?

Technology category photographTechnology

I'm making a small practice organiser for storage boxes. Two separately created Python lists both contain the single string “spare cables”. Comparing them with is gives False, so I thought one list might contain an invisible difference.

Python's built-in-types reference distinguishes equality, tested with ==, from object identity, tested with is. Python's comparison reference

I'm trying to compare the listed contents, not decide whether two physical boxes are the same box. How should I choose the comparison and check my understanding before I build more rules around this result?

Discussion

5 community replies

For these ordinary lists of strings, compare their contents with ==. The is question is whether both names refer to the same object. Two separate lists can have equal contents without being that one object.

Your interpretation of “same” needs to be explicit. Same contents, same Python object and same physical storage box are three different questions in this organiser. A comparison operator can't choose which of those the project means.

The False result from is doesn't provide evidence of invisible text differences. Investigate such a difference only if the appropriate value comparison also gives an unexpected result. Otherwise you'd be trying to explain a result that the identity test already accounts for.

A useful learning exercise is to compare two independently created equal lists, then compare two names deliberately assigned to one list. Write down the equality and identity results you expect before running it.

Include a later change to one list in that exercise and observe what the two names show. That helps connect identity to the objects your names refer to, rather than reducing the lesson to memorising that one operator happened to return False.

Join the discussion

More in Technology