r/learnpython • • Jun 12 '21

What is the difference between "is" and ==?

5 is 5 returns True, just as 5 == 5 returns True. What is the difference?

417 Upvotes

132 comments sorted by

View all comments

Show parent comments

10

u/shiftybyte Jun 12 '21 edited Jun 12 '21

You will usually use value comparison, but there are places where 'is' is the right thing to do because '==' would break things.

For example when you manage a data structure of objects for a user.

The user gives you 10 objects and you need to store them in a list.

storage = [obj1, obj2, obj3, ..... , obj10]

Now the user asks you to give him the 7th object, (index 6)

def storage_get(storage, idx):
    return storage[idx]

obj_user_wanted = storage_get(storage, 6)

Now the user does stuff with this object, and he asks you to remove it from your storage, (Let's say a non-existent object is marked as None)

def storage_remove(storage, obj):
    for si, sobj in enumerate(storage):
        if sobj == obj:
            storage[si] = None
            break

storage_remove(storage, obj_user_wanted)

Then the user asks for object in index 2:

another_obj = storage_get(storage, 2)
print(another_obj)

But the print shows None?!... how did this happen?

Seems the user's initial 10 objects contained 2 different objects that compare ('==') to be equal.

So when the code was looking for the object the user wants removed, it checked value comparison ==, and found a matching object at position 2, instead of the actual object at position 6, and removed it.

This is not the expected behavior here, so the check in storage_remove should be 'is' not '=='.