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

674

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

You have two identical blue cars in front of you.

They are the same model make and color.

The cars are equal, but the left car is not actually the right car...

Same with objects in memory, equals means they have the same value, "is" means it actually points to the same object.

172

u/[deleted] Jun 12 '21

So a = 5 and b = 5 but a is b returns False while a == b returns True?

15

u/xelf Elf Jun 12 '21 edited Jun 12 '21

So a = 5 and b = 5 but a is b returns False while a == b returns True?

Almost. In this case a is b as they point to the same object.

a = 1000
b = 1000

print(a is b)
print(a == b)
True
True

a = 1000
b = 999+1

print(a is b)
print(a == b)
False
True

here we get a 999 object stored in a different place, and then update it's value by 1. So it's actually a differnt object in memory.

In general is means they have the same id() (aka same object in memory)

To make it more confusing, cpython (the version of python almost everyone uses) will actually cache lower ints so if you change the 1000 above to a small int like 5, you would get 4 Trues.

In short is tells you if they have the same id().

a = "HI"
b = "hi"
c = b.upper()
b = b.upper()

print(id(a),a)
print(id(b),b)
print(id(c),c)

140116161981776 HI
140116161279736 HI
140116161279680 HI

8

u/wbeater Jun 12 '21 edited Jun 12 '21

It's actually easier if you explain it with lists because they always have their own id (are different objects):

a_list = [5]
b_list = [5]

print(a_list is b_list) # Output False, because they are different Objects
print(a_list == b_list) # Output True, because the == operator compares the values of two objects and these are the same in this case

now we bring in c_list but only as reference to one of those lists:

a_list = [5]
c_list = a_list

print(c_list is a_list)# Output True, because they both refer to the same object, to check for the value with the == operator is obsolete at this point 

u/BountyHunterJ

6

u/[deleted] Jun 12 '21

Thanks for the help. Also, this means when I alter a_list, c_list is also altered. How can I set c_list to the same value of a_list but not the same object? Completely unrelated but still curious.

7

u/K900_ SRE person // please don't DM me your questions Jun 12 '21

Make a copy: c_list = a_list.copy().

2

u/wbeater Jun 12 '21 edited Jun 12 '21

Yes you are correct, a_list and c_list refer to the same object if alter one of them you are altering the object.

.copy() function creates a new object with the same values. Alternatively if it's a list you can use the slice operator, but don't give a start stop parameter:

a_list = [5]
c_list = a_list.copy()

print(c_list is a_list) # Output False
print(c_list == a_list) # Output True

#Alternative with the slice operator

a_list = [5]
c_list = a_list[:]

4

u/[deleted] Jun 12 '21

Ooooh okay I understand thank you

3

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

and then update it's value by 1

Integers are immutable in python you don't actually update any of them, each math operation creates a new value.

Below test returns true because of caching like you said.

>>> a = 100
>>> b = 99+1
>>> a is b
True

1

u/xelf Elf Jun 12 '21

Yes, that is correct.

1

u/Blidf Jun 12 '21

a = 1000

b = 999 + 1

print(a is b)

print(a == b)

False

True

i try and i got your answer to

but if i change a and b like this, i got

a = 234

b = 233 + 1

print(a is b)

print(a == b)

True

True

why is that happen?

2

u/xelf Elf Jun 12 '21

cpython caches a lot of the smaller ints for optimization so they don't get new objects.

2

u/kwocca Jun 12 '21

Because for small numbers (i.e. between -5 and 256), it works differently than for other numbers.

It has been discussed in other replies on this thread

575

u/shiftybyte Jun 12 '21

In theory yes, in practice no, because python makes sure all small numbers are actually the same object (memory optimization)

>>> a = 5
>>> b = 5
>>> a is b
True

But it is correct for larger numbers:

>>> a = 487327634
>>> b = 487327634
>>> a is b
False
>>> a == b
True

417

u/wodahs1 Jun 12 '21

I hate this so much

194

u/[deleted] Jun 12 '21

I can understand why you hate it but there is a reason for it. With a high level language the pitfall is not knowing the implementation details and having surprising things like this come up, but it can also be a lot of fun to find out why this is the case, and once you figure it out it's like an 'AHA!' moment. It's due to an optimization called interning which is one of the first sections in this course: https://www.udemy.com/course/python-3-deep-dive-part-1/learn/lecture/7192348#overview

Can highly recommend all of that guys courses if you want to dive deep into the implementation details of Python.

26

u/jerryelectron Jun 12 '21

This course is great! Not for beginners!

8

u/LiarsEverywhere Jun 12 '21

You're right. I didn't know this, and my initial reaction was to hate it. Now I kind of love it. Thanks!

6

u/Ran4 Jun 12 '21

It's a bit fun, but it's also a failure that these type of things bubbles up into a high-level language.

20

u/Brian Jun 12 '21 edited Jun 12 '21

I would disagree. Caring about this here is actually probably a sign that you're doing something wrong, or misunderstanding what equality vs identity is and when it should be used. If this is the case, I think it's probably a good thing that you get surprised by stuff like this, rather than let that misunderstanding lead to more subtle errors, so "inconsistency" here might even be a good thing.

Eg. to return to OPs example of two blue cars, suppose you and a friend rent a car on seperate days from the same company. You both requested a car with a particular make, model and colour. Comparing notes, you notice that you both actually got the same car.

A month later, the same thing happens. But mysteriously, it turned out that this time, despite being the same otherwise, the cars had different number plates: apparently the company has multiple cars of that make/colour and it was just chance you got the same one last time.

Is it a failure of the company's policy that this happens? I mean, this is even worse than python, because getting the same car or not is effectively random, and python at least had a consistent system of giving the same number for low values.

But really, no - this is not a failure, and rather, it's perfectly to be expected. Your rental agreement said nothing about the identity of the car: you just asked the company to give you a car of a particular type. Whether it fulfils this request by giving the same car for multiple such requests, or multiple different cars isn't really something you need to, or should, care about. They're equivalent for pretty much all purposes.

In the same way, when you ask python to give you a "5", it's free to service that request any way it likes. It could make a new "5" object for every customer, or give the same "5" to everyone. Or even, like the company, randomly choose when to do so. The programmer shouldn't care. They should not assume it's "the same" 5, nor assume a different 5: it's just a 5, usable anywhere they need fiveness.

The reason python is free to reuse its 5's (among other things) like this is because numbers are immutable. You can't write to the five once python gives it to you (well, not "legally" - there are ways to hack this). This is where the analogy breaks down a little, since with the car company, being able to change the car might happen (ie. if we're spies who communicate by putting messages in the glovebox after renting the same car, it would matter whether we get the identical care or not, because we care about the mutation we made (putting a message in the glovebox).

But when you can't change things, there's no real difference between different objects having the same identity or not, unless you actually explicitly check their identity with is or id - but you shouldn't be doing that when you just want equality, because that's not what identity is for.

4

u/Crypt0Nihilist Jun 12 '21

usable anywhere they need fiveness.

There is something satisfying about things having the need for fiveness.

3

u/ianepperson Jun 12 '21

Well said.

1

u/Hope-full Jun 18 '21

Thank you for your contribution. Thoroughly enjoyed reading this.

4

u/Tech_John Jun 12 '21 edited Jun 12 '21

To hate something because you don't understand it?? Really?! C'mon, the analogy of the car IS exactly why this exists. 🤪

However, I could see that perhaps it would be better to make "is" ONLY work with objects. Then you wouldn't accidentally start using it as an equality as a noob.

... EDIT...

As some have noted, EVERYTHING is an object in python, so perhaps a better way to state my suggestion might be too constrain evaluation to the object itself and not pointers. But that's filled with peril as well.

In any case, as others have said, ONCE YOU UNDERSTAND the pythonic way of objects THEN it makes sense!

2

u/Brian Jun 12 '21

is does only work with objects. Numbers are objects too, not really fundamentally different from any other type of object.

1

u/DaveMoreau Jun 13 '21

Why should two literals for the same number be the same object or a different object just because they have the same value? Either approach seems valid to me. I wouldn’t count on either approaching being the implementation.

Now if you assign one variable to another, then I would expect them both to point to the same object.

2

u/[deleted] Jun 12 '21

However, I could see that perhaps it would be better to make "is" ONLY work with objects.

Not to wax semantic, but in Python everything is an object, including integers.

-1

u/Tech_John Jun 12 '21

Well said!

I guess perhaps a better way to say that would be "constrain 'is' to only look at the object itself and not value pointers"

But your valid point likely is the reason why "is" continues to work this way, and is confusing for noobs that haven't come to understand the pythonic way of things.

6

u/[deleted] Jun 12 '21

"constrain 'is' to only look at the object itself

As far as I understand, it is referencing the object itself. All integers from -5 to 256 in Python are constant objects that exist automatically, and for numbers outside that range the objects are only created when necessary. So if you do a = 5 and b = 5, both of those variables are referencing the same already existing object, but when you do a = 500 and b = 500, you're creating two distinct objects that happen to hold the same value. For instance...

>>> a = 5
>>> b = 5
>>> hex(id(a)), hex(id(b))
('0x7ffccc82c720', '0x7ffccc82c720')
>>>
>>> a = 500
>>> b = 500
>>> hex(id(a)), hex(id(b))
('0x1efdf12cb10', '0x1efdf12c9b0')

In the case of the former, a and b are the same object, and in the latter they are two different objects.

I don't have any formal comp sci background, I just write Python and make data go brrr, but as far as I can tell is is doing exactly what it should be, it's just that Python has a very specific way of handling integers that has nothing to do with the functionality of is, but happens to cause behavior with it that looks peculiar at first.

→ More replies (0)

1

u/[deleted] Jun 12 '21

Thank you!

!RemindMe 1 week

1

u/RemindMeBot Jun 12 '21

I will be messaging you in 7 days on 2021-06-19 21:26:06 UTC to remind you of this link

CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


InfoCustomYour RemindersFeedback

13

u/tom1018 tomfaulkner Jun 12 '21

In addition to what others said, a decent linter will tell you if you did is with an int and that you should be doing ==.

12

u/TSM- Never slipped a dict comprehension in my lambda before, but Jun 12 '21

In python 3.8+ you get a syntax warning now.

x = 200
if x is 200:
    print("It's 200!")

results in

SyntaxWarning: "is" with a literal. Did you mean "=="?

The compiler now produces a SyntaxWarning when identity checks (is and is not) are used with certain types of literals (e.g. strings, numbers). These can often work by accident in CPython, but are not guaranteed by the language spec. The warning advises users to use equality tests (== and !=) instead.

4

u/tom1018 tomfaulkner Jun 12 '21

That's great. I hope they'll do that with anything similar in the future.

I would pay an extra second in compile time to avoid troubleshooting bugs caused by forgetting an implementation detail.

13

u/ericula Jun 12 '21

why?

54

u/Acquiesce67 Jun 12 '21

Because the behaviour is unpredictable. You need to understand what’s going on under the hood. Keeping in mind such small nuances can be a pain. A language is a tool and a tool should have predictable actions for my commands.

Python is awesome, I use it everyday but it’s got some pitfalls like this example.

12

u/Vaphell Jun 12 '21

You need to understand what’s going on under the hood.

or you just need to understand that the value comparison == should be used 99% of the time in general, and for numbers specifically 100% of the time.

1

u/Acquiesce67 Jun 14 '21

Think of someone who’s learning Python (either as their first language or not). They start the REPL, write in 5 is 5 and it says True. Are they correct assuming this is an accepted way for integer comparison ? Yes, they are because the language does what they expect/experiment. However, after a certain integer size their code will fail. This is what unpredictability is. No need to fuss.

2

u/Vaphell Jun 15 '21

what can I say, ignorance can lead you astray. That said, the expectation that complete noobs can learn programming without ever reading any documentation, just by throwing shit at the wall and hoping it sticks, is completely unrealistic.
This is a problem that is solved in 20 seconds of googling, ie no problem at all.

1

u/Acquiesce67 Jun 15 '21

I’m trying to say that the is operator should raise an Exception when used on integers to guard the user. But this is just my opinion, I’m not a language designer 🤷🏼‍♂️

→ More replies (0)

19

u/Dogeek Expert - 3.9.1 Jun 12 '21

Because the behaviour is unpredictable. You need to understand what’s going on under the hood. Keeping in mind such small nuances can be a pain. A language is a tool and a tool should have predictable actions for my commands.

It's that way for a reason. Most numbers in programming are quite small actually. Having the small numbers (under 256) be constants improves performance by not having to allocate memory for that number (which is a time consuming process). It's also why lists work by reference in python. In most cases, it fulfills its role as is, but it improves performance by not having to reallocate the memory for the list everytime you decide to rename the variable (which happens more often than you think).

Python's number 1 critic is that it's a slow language. These odd behaviours (actually, they make a lot of sense if you've ever worked with C) are essential. They make the language significantly more performant. It's fast enough now to be used instead of R for data science and statistical analysis.

-2

u/MrozW Jun 12 '21

Having the small numbers (under 256) be constants improves performance by not having to allocate memory for that number

Ok, fine. But "a is b" should be the same in ANY curcumstances and not depending on the input. BTW it is not the only weird thing in Python e.g. the ternary conditional operator "a if condition else b" I really find horrible from syntax perspective.

10

u/gabzox Jun 12 '21

I mean theoretically it does have the same output it is just not what YOU expect.

IS refers to location in memory. If you are comparing values == is correct to use.

If you wanted to see if the two values have the same location (if they are the same object) then IS would be what you use.

I

3

u/[deleted] Jun 12 '21

This shit is all crazy to me. Newcomer trying to grasp what y’all are saying 🤯

0

u/Jorrissss Jun 12 '21

You’re using ‘is’ incorrectly if you think this is a problem imo.

8

u/flying-sheep flying-sheep Jun 12 '21

This is no pitfall. Using is is pretty rare. The only cases where I use it in practice is sentinels: thing is None or empty = object(); thing is empty.

5

u/antiproton Jun 12 '21

It's not unpredictable, you just don't happen to know the limit. And for all intents and purposes, it's irrelevant. This kind of limit only applies to primitives. Any other object works exactly as described.

3

u/Vaphell Jun 12 '21

This kind of limit only applies to primitives.

primitives in python? no such thing

1

u/Acquiesce67 Jun 14 '21

Well, switch the perspective: why do I need to know (and keep in mind) a certain limit?

1

u/DaveMoreau Jun 13 '21

I don’t see a problem with this behavior for literals. We should not be making assumptions about whether or not a language creates a new object for equal values.

On the other hand, I would expect int(5) to always create a new object, since that is a class constructor. I believe it still reuses objects in that case, which definitely goes against reasonable expectations.

Regardless, I can’t actually think of a use case where this would matter.

1

u/[deleted] Jun 12 '21 edited Jun 13 '21

What is unpredictable about it?

edit:

One is, effectively, saying is this apple in my lunch box the exact apple I took out of the fruit basket. The other is this thing equivalent to an apple.

It's perfectly predictable and it's comparable to many other languages. For example, java has apple == some_other_apple and apple.equals(apple).

17

u/DancingBestDoneDrunk Jun 12 '21

What's small and what's large?

15

u/ericula Jun 12 '21

It's implementation dependent and not something you can rely on. But it shouldn't really matter. When comparing integers you should always be using == anyway.

6

u/X_Shiverz_X Jun 12 '21 edited Jun 12 '21

If I recall correctly, small is anything below 256. May be wrong though

Edit: Just looked it up, and basically "small" here is anything between -5 and 256 including

5

u/DancingBestDoneDrunk Jun 12 '21

-256 and 256 would be logical, but that's just.... Predictable, but not logical

→ More replies (0)

2

u/MegaIng Jun 12 '21

-5 to 255 (may be of by one or two)

1

u/alienscape Jun 12 '21

Holy cow, I do too! How do I pound this into my brain?

1

u/[deleted] Jun 13 '21

Don't. Right now you're using numbers, but later you will likely be using objects and sometimes it's good to know whether two objects are actually the same object in memory or not. I can't think of an example right now because it's been a while since I've programmed in python, but in C#, I can do:

if (someReference is object) { /* blah blah blah */ }  
else { /* throw some kind of error because that object should never not be an object and something has gone horribly wrong! */ }  

Bottom line, it exists for a VERY good reason.

1

u/backtickbot Jun 13 '21

Fixed formatting.

Hello, GinoMan2440: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

16

u/[deleted] Jun 12 '21

This gets even weirder when you compare different python versions

In python >= 3.7

>>> 1000 + 1 is 1001
True

In python 3.6

>>> 1000 + 1 is 1001
False

20

u/PaulRudin Jun 12 '21

Yeah - in general the occasions on which you want to use is are pretty limited. It's a common idiom to see if foo is None where foo is an optional argument with default value None, but None is guaranteed to be the only object of that type (i.e. foo is bar will always test True if foo and bar are both None).

3

u/MatosV Jun 12 '21

Wow, I didn't know that. Thanks!

2

u/bmcle071 Jun 12 '21

I was trying to answer this question and went and put some small numbers into the interpretor and was really surprised to find this. Seriously confusing.

1

u/frederik88917 Jun 12 '21

Piggybacking on this, most modern programming languages hold a integer cache, approximately up to 200 numbers, that will always exist in memory and it will be used to reference the value when an user creates a small integer.

This helps to reduce the total amount of memory used by the programs by not putting in memory all instances of small numbers, just references to the values in the cache

2

u/Brian Jun 12 '21

Piggybacking on this, most modern programming languages hold a integer cache

Nitpick: it depends on the language. A lot of languages have a different model in which integers are value types and treated differently, and even when they're ostensibly reference types, they may use a tagged pointer system where integers are held directly. Both of these obviate the need for an integer cache. And sometimes there are other reasons it isn't done.

Eg. Java does have value types for integers, but also has boxed versions (ie int vs Integer) for which it does have a small integer cache. However, C#, though pretty similar, I think doesn't have an integer cache - I think because the .Net bytecode allows potentially mutating boxed integer values, though C# itself doesn't use this.

1

u/[deleted] Jun 12 '21

such wisdom!

1

u/FL14 Jun 12 '21

Yo... Wtf

1

u/IamFromNigeria Jun 12 '21

Hey, Nice one.i wish to ask you a question on Excel Tips

0

u/[deleted] Jun 12 '21

[deleted]

20

u/Yoghurt42 Jun 12 '21

It's not inconsistent. is will always check for identity, == will always check for equality.

Using the wrong operator and still getting the correct result in certain cases is not inconsistent.

Just because 0+0 = 0*0 and 2+2 = 2*2 doesn't mean you can use * when you want to add, because you tested it with 0 and 2, and then complain that it is not doing what you expect when you use it with other numbers.

5

u/Poddster Jun 12 '21

It's not inconsistent?

0

u/[deleted] Jun 12 '21

[deleted]

2

u/ianepperson Jun 12 '21

“is” should never been used to test numbers, unless you’re doing something advanced.

3

u/[deleted] Jun 12 '21

Great, I understand that. But why does it still work then? Some people might be unaware of that and misuse it.

3

u/ianepperson Jun 12 '21

I mean, Python could be updated to throw an error if you try to use “is” for numbers, but that seems silly to me. “a is b” is just shorthand for “id(a) == id(b)”

“is” can be very useful when comparing objects, lists and dictionaries.

6

u/Brian Jun 12 '21

“a is b” is just shorthand for “id(a) == id(b)”

>>> [] is []
False
>>> id([]) == id([])
True

Checkmate, idtheists!

3

u/TSM- Never slipped a dict comprehension in my lambda before, but Jun 12 '21

Since python 3.8 you now get a syntax warning:

>>> x = 200
>>> x is 200
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?

2

u/[deleted] Jun 12 '21

Ohh, that's great. Issue solved.

2

u/Intrexa Jun 12 '21

Not in all cases

Python 3.8.5 (default, May 27 2021, 13:30:53) 
[GCC 9.3.0] on linux

>>> x = 100
>>> a = 100
>>> x is a
True
→ More replies (0)

1

u/Ran4 Jun 12 '21

Then it should probably raise.

5

u/gabzox Jun 12 '21

Not inconsistent. You are thinking of "is" wrong.

12

u/OriginalTyphus Jun 12 '21

Wow, TIL.

I always thought that you just use "is" to compare against None and boolean values. So it reads more like the english language.

Now it makes sense in another way. Thanks!

7

u/the-berik Jun 12 '21

So with "is" you compare the object, with "==" you vompare the value?

And what would be appropriate usecases for both?

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 '=='.

4

u/Yoghurt42 Jun 12 '21 edited Jul 23 '21

is checks for identity, == for equality, in the mathematical sense.

Let's say you and your neighbor both drive a blue 2011 Toyota.

(Here's where the "looseness" of English language comes to bite us, because we pretty much use "it's the same" and "it's identical" as synonyms. Apparently, the correct word for "those two things are identical in the mathematical sense" to use would be "selfsame" or "one and the same".)

So, you and your neighbor drive the same car (color, model), they are equal. However, they are not selfsame. That would be the case if you and your neighbor would share the same car, then you would drive the selfsame car.

Staying with this example, car == your_car would check if the car in question is a blue 2011 Toyota, while car is your_car would only be true if car is your own car, not your neighbor's or any other blue 2011 Toyota.

In Python, you rarely will use is, basically only for

  1. is False or is None, or

  2. sentinel values

For 1., you don't use if a == None because it could lead to problems if a is an object that defines equality weirdly.

Stupid example:

class AlwaysEqual:
    def __eq__(self, other):
        return True

wtf = AlwaysEqual()
print(wtf == None) # True
print(wtf is None) # False

For 2. sometimes you want to have a default parameter or a placeholder, but where None would be a valid value. For example, let's assume you want to write a caching decorator for function calls, a function can return every possible value, but you still need to decide whether the cached value is a placeholder or not:

sentinel = object()
cached_value = sentinel

# now we want to check whether we need to call the expensive function
if cached_value is sentinel:
    cached_value = expensive_function()
return cached_value

We could not use == here because the function might return an object that says it is equal to our object, and therefore expensive_function would be called every single time. (There are more elegant solutions for function caches that make use of Python's dynamic nature, this is just an example.)

5

u/Marvinx1806 Jun 12 '21

Another example:

It's like saying tom and peter wear the same shirt.

You could understand it like that each of them has an own shirt but both Look exactly the same. Or you could understand it like that they both stuck in one shirt.

Basically the shirt of peter equals the shirt of tom or the shirt of peter is actually the same as toms.

1

u/shiftybyte Jun 12 '21

That's a bit confusing, are there two shirts? or one shirt? do they wear it together? or each wears his own shirt?

2

u/Marvinx1806 Jun 12 '21

Yeah that's pretty much the difference, isn't it?. I'm sorry, english is not my main leguane. In german, there are two diferent words for rather it is the same shirt in terms of color and stuff or the same shirt in terms of actually the same.

2

u/gabzox Jun 12 '21

Maybe to clarify.

He is saying if there are two shirts...but are the same then "is" would return false but == true

If they are both wearing the same shirt

Then "is" would be true and == would be true.

So the answer that question you need to use "is"

2

u/blindsho0t Jun 12 '21

B-E-A-U-tiful

2

u/[deleted] Jun 12 '21

This is an awesome explanation

2

u/[deleted] Jun 12 '21

Great explanation, thank you

2

u/MisterBungle Jun 12 '21

That’s a pretty perfect analogy

2

u/-SPOF Jun 12 '21

That is the best explanation I have ever seen.

1

u/Impronoucabl Jun 12 '21

Does that mean 'is' is a teeny-weenie-bit faster than '==', since it's not actually evaluating the value?

6

u/shiftybyte Jun 12 '21

Yes, 'is' is usually faster than '==' but may or may not get you the desired results.

4

u/Poddster Jun 12 '21

Yes , but they don't have the same usecase so comparing their comparison speeds isn't that useful

1

u/[deleted] Jun 12 '21

Wow what a trivia

1

u/Not-an-Uchiha Jun 12 '21

I read this exact same analogy in a Python book. Is it from there, or did you come up with it yourself?

1

u/shiftybyte Jun 12 '21

Came up with it, what book did you see this in? chapter number? i'd like to take a look too...

1

u/Not-an-Uchiha Jun 12 '21

Nice, I read it in Think Python or Problem Solving with Algorithms and Data Structures using Python (both free, Runestone books I used simultaneously).

1

u/DezXerneas Jun 12 '21

So what's the difference between === and is?

56

u/Euphoric-Quality-424 Jun 12 '21

5 == 5.0 returns True , because they are mathematically equal.

5 is 5.0 returns False , because one is an int and the other is a float, so they cannot both be stored at the same memory location.

3

u/CloudNoob00 Jun 12 '21

Thank you.

1

u/TciddaecnacT Jun 12 '21

Would it be fair to say:

'is' evaluates for exactness

'==' evaluates for sameness

1

u/Euphoric-Quality-424 Jun 13 '21 edited Jun 13 '21

"exactness" is a bit vague. In purely mathematical terms, 5 and 5.0 are "exactly" equal - they are just different representations of the same number. (Any disagreement about this would be more philosophical than mathematical.)

Also, "sameness" can be subjective: it depends on how the == operator is defined for the objects in question. One good example of this is NaN ("not a number") as defined in modules like math, numpy, etc.

Code:

from math import nan
print(nan is nan)
print(nan == nan)

Output:

True
False

Explanation:

There is only one nan object, so nan is nan returns True.

But when you have two variables that both have the value nan, that doesn't mean they are "equal" (they are just equally meaningless in numerical terms). So nan == nan returns False.

0

u/[deleted] Jun 12 '21

[deleted]

1

u/Brian Jun 12 '21

251 is 251 is False

Actually, that'll still be True. One reason is that the cache goes up to 256, so this is still in the cached range, but even if you did 260 is 260, it'd still say True, because python will compile that line as one compilation step, and notice that the same values are used in multiple places and reuse the object. You'd need to do something like split it over multiple lines:

>>> a = 260
>>> a is 260
False

16

u/[deleted] Jun 12 '21

10

u/[deleted] Jun 12 '21

Is compares id while == compares value

4

u/lele3000 Jun 12 '21

Besides what others answered, one practical way of looking at it is that you can overload == but not is.

For example:

class MyClass:
    def __init__(self, value):
        self.value = value

    def __eq__(self, value):
        return self.value == value

a = MyClass(2)
a == 2 % returns True
a is 2 % returns False and displays warning

a = MyClass(None)
a == None % returns True
a is None % returns False

This is for example often used in numpy where == is overloaded to perform vector wise comparison and also returns a vector, while is performs object wise comparison:

import numpy as np

a = np.array([None, None, None])
a == None % returns array([ True,  True,  True])
a is None % returns False

4

u/____candied_yams____ Jun 12 '21

I think this is right:

  • a == b checks equality: a.__eq__(b)

  • a is b checks identity: id(a) == is(b)

3

u/py_vel26 Jun 12 '21 edited Jun 12 '21

I'm glad I came across this post. I'm new to Python but it makes sense to me. A dollar bill is not 4 quarters but they have equal value. $1 is $1(4 quarters) FALSE or $1 == $1(4 quarters) TRUE

2

u/mayankkaizen Jun 12 '21

Every thing is object in Python and every object has a value, a type and an ID. The is operator checks if both objects have same ID (and therefore same value and type). If this returns True, it means both objects are one and same.

OTOH, == operator merely checks for value. It doesn't say anything about ID.

a = [1,2]
b = [1,2]
c = "foo"
d = "foo"
a == b  #True
a is b   #False, see below
c is d   #True
c == d #True

Note that since list is of mutable type, above a and b are guaranteed to refer two different objects even though they have the same values. Hence == returns true but is returns false.

For strings and numbers in range [-5,256], operation

`c` is `d` #if both have same value

will always return True. The same is not true for mutable types.

1

u/Moraedka Jun 12 '21

If you had tried coding in JavaScript, there is a '===' comparison operator. What's the difference of === and ==?
The answer is simple:

  • == compares both of the objects' values. Returns a true boolean value if both have the same value, regardless of data type.

  • === compares both of the objects values and data types. Returns a true boolean value if both have the same value and data types.

Since JavaScript is a dynamically-typed language, he has to implement type comparison. Same goes for Python, except replacing === with is.

If we have some float x and int y with similar values (assumed to be 69, nice), then:

x is y
>>> False

x == y
>>> True

1

u/backtickbot Jun 12 '21

Fixed formatting.

Hello, Moraedka: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.

1

u/DrMaxwellEdison Django and stuff Jun 12 '21

5 is 5 is equivalent to id(5) == id(5). Have a look at the id() built-in function for details.

Essentially, is tests that two objects are the same object in memory. id() returns that memory identifier.

The reason 5 is 5 still returns True is because small integers and strings are treated as singletons in memory for convenience. Python does not bother to create two different objects to represent those small values: it just finds the first one cached in memory and returns that one.

If you tried 12345678 is 12345678, you would likely get a False (on mobile, cannot double check).

0

u/[deleted] Jun 12 '21

[deleted]

9

u/[deleted] Jun 12 '21

Just completely and utterly wrong. Is compares whether they refer to the same object. == compares the values.

24

u/[deleted] Jun 12 '21

[removed] — view removed comment

1

u/gaurav_lm Jun 12 '21

Yes this. While there are great explanation here, I'd recommend OP to learn about id( ) method.