Python has several operators that can be used to carry out comparisons between two objects. The operator
!= is one of them. What does != mean in python? What is the difference between
is not in Python? This article will discuss these operators.
What does != mean in Python?
The comparison operator
!= compares two objects to see if they are not of the same value. It returns a boolean; if it returns
True, it means that the two objects are not equal, if it returns
False, it means that the two objects are equal.
Some examples will illustrate the use of the
The following code block will print out
Not Equal since
y are not referring to the same value.
x = 1 y = 2 if x != y: print("Not Equal") else: print("Equal")
If we make
y to refer to the same value, the code block will print
x = 2 y = 2 if x != y: print("Not Equal") else: print("Equal")
The next example assigns the same list value to variables
y. The code block will print
y refer to the same value.
In other words, the condition
x != y is not satisfied, the
else part will be executed.
x = [3, 'Apple', True] y = [3, 'Apple', True] if x != y: print("Not Equal") else: print("Equal")
If we change the list values so that x and y are not referring to the same value, the code block now returns Not Equal. This is because the condition x != y is now satisfied.
x = [3, 'Apple', True] y = [3, 'Banana', True] if x != y: print("Not Equal") else: print("Equal")
!= operator versus is not operator
There is another comparison operator in Python that could be confused with the
is not operator.
!= compares values for Equality, while
is not compares values for Identity. What do these concepts mean?
Two variables are Equal when they refer to the same value. So, two objects are equal if they refer to the same object (in the same memory address), or the objects are copies of each other, but in different memory addresses.
On the other hand, two objects are Identical when they are referencing the same object in memory, or the same memory location.
The example below will show the difference between the two operators.
z = [1, 3, 5] a = z b = z c = [1, 3, 5] print(a is not b) # will print False print(a != b) # will print False print(a is not c) # will print True print(a != c) # will print False
a is not b will return
False because both variables are pointing to the same object in memory – the object referred to by the variable
Also, the operation
a != b will return
False since the variables
b pointing to the same memory object implies that
b have the same value.
On the other hand,
a is not c will return
True because the variable
c is now referring to a totally different memory object from
z. As a result,
c is referring to a very different memory object. However, since
c have the same value,
a != c will return
We have come to the end of this short Python article. We hope you have been able to clarify some misconceptions. You can read more interesting Python articles and get Python help on our website.