0

Please do not mark duplicated YET. I did read this Python is vs ==

I have read around and noticed == vs is that is checks if same memory location and == is used to compare two values but recently I was using is by accident BUT to me it's acting weird and I am don't really understand why though.

I am trying to parse a url path to see if the page number matches for example

a = '9'
b = '/category-1-11-9.html'
c = b.split('.html')[0].split('-')[-1]
print(a is c, ' bool')  # this gives True


a = '10'
b = '/category-1-11-10.html'
c = b.split('.html')[0].split('-')[-1]
print(a is c, ' bool')  # this gives False

I figured if the number is a single digit, I get True as return and if number is 10 or more I get False

I tried to print both a and c to see their type and value, ended up both typeandvalue` are the same. But why with a single digit it gives True and double digits it gives False?

I am quite confused with this even after reading articles about is

Using python version 3.7.7

Dora
  • 6,776
  • 14
  • 51
  • 99
  • 1
    TL;DR: never use `is` where you mean to use `==`. Only ever expect `is` to return any particular result if you're testing objects you have personally assigned to another variable (e.g. `a = b; assert a is b`). In any other situation, you want to test for *equality*, not *identity*. – deceze Sep 16 '20 at 08:11
  • 1
    In how far do you consider this weird? Python makes no guarantees about the uniqueness of its builtin immutable types – the same value *may* be always the same object, just as it *may* be not. *Why* did you expect a different behaviour? – MisterMiyagi Sep 16 '20 at 08:22
  • @MisterMiyagi thanks for that explanation, I get what you mean now – Dora Sep 16 '20 at 08:35
  • From Mark Byers response in the link you reference: _You should use `==` to compare two values. You should use `is` to see if two names are bound to the same object_. Python implementations have objects for common items, such as small integers and perhaps (as in your example) individual character strings, so whilst these _may_ point to the same object, you can't rely on that behaviour except for testing against `None`, `True` or `False` – Andrew Richards Sep 16 '20 at 08:45

0 Answers0