double equals vs is in python
is
checks that 2 arguments refer to the same object, ==
checks that 2 arguments have the same value. dir()
returns a list
which contains the same data for both foo
and 10
, but the actual list
instances for the 2 things are different.
Is there a difference between == and is?
is
will return True
if two variables point to the same object (in memory), ==
if the objects referred to by the variables are equal.
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
>>> b == a
True
# Make a new copy of list `a` via the slice operator,
# and assign it to variable `b`
>>> b = a[:]
>>> b is a
False
>>> b == a
True
In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work:
>>> 1000 is 10**3
False
>>> 1000 == 10**3
True
The same holds true for string literals:
>>> "a" is "a"
True
>>> "aa" is "a" * 2
True
>>> x = "a"
>>> "aa" is x * 2
False
>>> "aa" is intern(x*2)
True
Please see this question as well.
String comparison in Python: is vs. ==
For all built-in Python objects (like
strings, lists, dicts, functions,
etc.), if x is y, then x==y is also
True.
Not always. NaN is a counterexample. But usually, identity (is
) implies equality (==
). The converse is not true: Two distinct objects can have the same value.
Also, is it generally considered better to just use '==' by default, even
when comparing int or Boolean values?
You use ==
when comparing values and is
when comparing identities.
When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is
, but don't rely on it.
For boolean values, you shouldn't be doing comparisons at all. Instead of:
if x == True:
# do something
write:
if x:
# do something
For comparing against None
, is None
is preferred over == None
.
I've always liked to use 'is' because
I find it more aesthetically pleasing
and pythonic (which is how I fell into
this trap...), but I wonder if it's
intended to just be reserved for when
you care about finding two objects
with the same id.
Yes, that's exactly what it's for.
Why there is 2 equals signs ia an if statement on python
== is a comparison operator
You can use == to see whether any two items as long they are the same type are equivalent:
a = 2
if a == 2: # Compares whether a is equal to 2. this is true.
print(a)
When using ==, if the two items are the same, it will return True. Otherwise, it will return False.
And with your code,
if op == "+": print(num1 + num2)
Means if the op variable is same as the "+", print the result of num1 + num2
Is there any python operator that equivalent to javascript triple equal?
The ordinary ==
operator in Python already works much like the ===
operator in JavaScript, in that it won't do string conversions. However, it does not compare types.
>>> 1 == '1'
False
>>> 1 == 1.0
True
>>> 1 == True
True
So we would say that Python doesn't have an exact equivalent to the JavaScript ==
or ===
operators. The way Python uses ==
, without a ===
operator, is the norm. JavaScript (and PHP) are a bit unusual.
This last bit about bool
might be a bit surprising, but bool
is a subclass of int
in Python.
Python: assignment operator and double-equals in the same line
It is allowed, your problem is, that is
is a reserved keyword, e.g.
foo is None
Rename your variable ;)
Python None comparison: should I use is or ==?
Summary:
Use is
when you want to check against an object's identity (e.g. checking to see if var
is None
). Use ==
when you want to check equality (e.g. Is var
equal to 3
?).
Explanation:
You can have custom classes where my_var == None
will return True
e.g:
class Negator(object):
def __eq__(self,other):
return not other
thing = Negator()
print thing == None #True
print thing is None #False
is
checks for object identity. There is only 1 object None
, so when you do my_var is None
, you're checking whether they actually are the same object (not just equivalent objects)
In other words, ==
is a check for equivalence (which is defined from object to object) whereas is
checks for object identity:
lst = [1,2,3]
lst == lst[:] # This is True since the lists are "equivalent"
lst is lst[:] # This is False since they're actually different objects
Python in vs ==. Which to Use in this case?
Performance: in is better
timeit.timeit("pub='1'; pub == 1 or pub == '1'")
0.07568907737731934
timeit.timeit("pub='1'; pub in[1, '1']")
0.04272890090942383
timeit.timeit("pub=1; pub == 1 or pub == '1'")
0.07502007484436035
timeit.timeit("pub=1; pub in[1, '1']")
0.07035684585571289
#other options
timeit.timeit("pub='1'; pub in (1,'1')")
0.04643988609313965
timeit.timeit("pub='1'; pub in {1,'1'}")
0.17076611518859863
timeit.timeit("pub=1; pub in (1,'1')")
0.047419071197509766
timeit.timeit("pub=1; pub in {1,'1'}")
0.1770930290222168
So, {} > or > [] > ()
based on performance.
Practice: in
is preferred as it is less to type. (), [], {}
equally good based on practice
Memory:
sys.getsizeof([1,"1"])
88
sys.getsizeof("1",1)
38
#other options
sys.getsizeof(("1",1))
72
sys.getsizeof({"1",1})
232
So, {} > [] > () > or
based on memory
Although not asked,, good to know:
Functionality: Value equality and not reference equality
in
is just sequential checking equality ==
. So similar. in
uses ==
and not is
.
What I mean to say is this:
>>> a = [1,2,3]
>>> b = [1,a]
>>> b
[1, [1, 2, 3]]
>>> 1 in b
True
>>> a in b
True
>>> [1,2,3] in b
True
So it is implemented not like this:
>>> for i in b:
... print [1,2,3] is i
...
False
False
is
will return True if two variables point to the same object, ==
if the objects referred to by the variables are equal. in
uses ==
Why does comparing strings using either '==' or 'is' sometimes produce a different result?
is
is identity testing, and ==
is equality testing. What happens in your code would be emulated in the interpreter like this:
>>> a = 'pub'
>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False
So, no wonder they're not the same, right?
In other words: a is b
is the equivalent of id(a) == id(b)
Related Topics
Do I Need to Import Submodules Directly
How to Plot Multi-Color Line If X-Axis Is Date Time Index of Pandas
How to Replace Back Slash Character with Empty String in Python
Python: How to Run Eval() in the Local Scope of a Function
Python Generator That Groups Another Iterable into Groups of N
How to Log Server Errors on Django Sites
Django JSONfield Inside Arrayfield
Combining Two Series into a Dataframe in Pandas
Take Multiple Lists into Dataframe
How to Add a Question Mark [] Button on the Top of a Tkinter Window
How to Open Multiple Webpages in Separate Tabs Within a Browser Using Selenium-Webdriver and Python
In Python, How Does One Catch Warnings as If They Were Exceptions
My Py2App App Will Not Open. What's the Problem
Create a Main Loop with Tkinter
What Is the Most Efficient Way of Counting Occurrences in Pandas