In today’s post, we’ll learn to do “not equal” comparisons in Python.
Say we want to determine if two values are not equal in Python, there are two ways to do it:
- Using the
!=
operator - Using the
not
operator
Table of Contents
How to do not equal comparisons in Python
Using the != operator
The most direct way to determine if two values are not equal in Python is to use the !=
operator (Note: There should not be any space between !
and =
).
The !=
operator returns True
if the values on both sides of the operator are not equal to each other.
For instance, if you run the code below:
print(5 != 7) print(5 != 5) x = 12 print(x != 7) print(x != 12)
you’ll get the following output:
True False True False
Line 1 gives us True as 5 is not equal to 7.
On the other hand, line 2 gives us False
as 5 is equal to 5. Hence, 5 not equal to 5 is False
.
On line 4, we declare a variable called x
and assign 12 to it.
Next, we use the !=
operator to compare x
with 7 and 12.
Line 5 gives us True
as x
(which is 12) is not equal to 7. On the other hand, line 6 gives us False
as x
is equal to 12. Hence, x
not equal to 12 is False
.
Using the not operator
Besides using the !=
operator to determine if two variables/values are not equal in Python, we can also use the not
operator. The not
operator inverts the Boolean value after it.
For instance,
print(not True)
gives us
False
as the not
operator in front of True
inverts True
to False
.
To compare if two values are not equal using the not
operator in Python, we can do it as follows:
print(not 5 == 5) print(not 5 == 7) x = 12 print(not x == 3) print(not x == 12)
If you run the code above, you’ll get the following output:
False True True False
not 5 == 5
is False
as 5 == 5
is True
. Hence, not True
gives us False
.
On line 2, not 5 == 7
is True
as 5 == 7
is False
.
Similarly, on line 5, not x == 3
is True
as x == 3
is False
(since x
equals 12).
Last but not least, on line 6, not x == 12
is False
as x == 12
is True
.
What does <> mean in Python?
If you have programmed in other languages before, or you have seen code written in Python 2, you may have come across the <>
operator.
In Python 2, besides the !=
operator, we can use the <>
operator to compare if two values are not equal.
This operator is the same as the !=
operator, both of which stand for not equal. For instance, both 5 <> 7
and 5 !=7
give us True
in Python 2.
However, <>
has been deprecated in Python 3. Hence, for compatibility reasons, you should stick to !=
(instead of <>
) if you want to do not equal comparisons in Python.
Datatypes Matter
When determining if two values are not equal in Python, note that datatypes matter.
For instance, suppose we have
print(5 != '5')
we’ll get True
as the output as 5 is a number while '5'
is a string. Hence, 5 is not considered to be equal to '5'
.
This point is important to note when we accept inputs from users using the input()
function. A common mistake beginners make is forgetting that the input()
function returns the input as a string. Hence, if you want to compare the input against a number, you need to either convert the input to a number or convert the number to a string.
For instance, if you run the following code:
userInput = input('What is the smallest prime number? ') if userInput != 2: print('Wrong') else: print('Correct')
and enter 2 when prompted, you’ll get the following output:
What is the smallest prime number? 2 Wrong
We get ‘Wrong’ as the output because userInput
is a string ('2'
). Hence, userInput != 2
becomes '2' != 2
, which is True
.
As a result, the if
block is executed.
To compare if userInput
is not equal to 2, we need to convert it to an integer. In other words, we need to change line 3 above to
if int(userInput) != 2:
Alternatively, we can convert 2 to '2'
, as shown below:
if userInput != '2':
is not vs != in Python
Another important concept to discuss when determining if two values are not equal in Python is the difference between equality and identity.
In Python, two variables may have equal value, but different identities. We discussed this previously in the blog post: How to Compare Strings in Python.
Say we have two strings – str1
and str2
– as shown below:
str1 = 'Hello' str2 = ''.join(['H','e','l', 'l', 'o']) print(str1) print(str2) print(str1 != str2) print(str1 is not str2)
If you run the code above, you’ll get the following output:
Hello Hello False True
Notice that both str1
and str2
have the same value? When we print their values on lines 4 and 5, we get 'Hello'
as the output for both variables.
In addition, when we compare str1
with str2
on line 7 using the !=
operator, we get False
.
However, when we compare them using the is not
operator on line 8, we get True
as the output.
The reason for this is the is not
operator compares a difference in identity, not just a difference in value. It returns True
if the two strings on both sides have different values OR different identities.
Although str1
and str2
have the same value, they have different identities. This is because the two strings are stored in different memory locations.
You can verify that using the Python id()
function. This function returns the unique identifier associated with an object (such as a string), based on the memory location of that object.
If you run the code below:
str1 = 'Hello' str2 = ''.join(['H','e','l', 'l', 'o']) print(id(str1)) print(id(str2))
You’ll get an output similar to what is shown below:
68639232 30536096
From the output above, you can see that id(str1)
returns a value that is different from id(str2)
. Hence, str1 is not str2
returns True
as the two strings have different identities.
The example above illustrate that if you are only interested in comparing if two variables have different values in Python, do not use the is not
operator. Instead, use the !=
operator, or the not ==
operator.
Determining if a Python variable is not equal to multiple values
Next, let’s learn to compare if a Python variable is not equal to multiple values.
There are three main methods to do it:
Using and
You can combine multiple comparison statements using the and
keyword:
x = 5 if x != 1 and x != 2 and x != 3: print('Not equal') else: print('Equal')
Here, we compare x
against three values – 1, 2 and 3.
If you run the code above, you’ll get
Not equal
as the output as x != 1 and x != 2 and x != 3
is True
and the if
block is executed.
Using not
Alternatively, another way to compare a variable against multiple values is to use the not
keyword:
x = 5 if not (x == 1 or x == 2 or x == 3): print('Not equal') else: print('Equal')
Here, we use parenthesis (on line 3) to indicate that we want the program to evaluate
x == 1 or x == 2 or x == 3
first.
If x
does not equal 1, 2 or 3, the condition above evaluates to False
.
The if
condition on line 3 becomes True
(as not False
is True
) and the if
block is executed.
If you run the code above, you’ll get
Not equal
as the output.
Using not in
The third (and recommended) way to compare if a variable is not equal to multiple values in Python is to use the not in
operator.
The not in
operator returns True
if a certain value is not in a specified sequence (such as a list). For instance, to determine if the value of x
is not 1, 2 and 3, we can use the code below:
x = 5 if x not in [1, 2, 3]: print('Not equal') else: print('Equal')
we’ll get
Not equal
as the output.
Using not equal in a Python loop
Not equal operators can be very useful in a Python loop.
A typical use of not equal operators in a loop is when we need to repeatedly prompt users to take a certain action as long as a variable is not equal to a stated value.
For instance, we may repeatedly prompt users to enter their input or enter -1 to end the program. This can be accomplished using the code below:
userInput = 0 while userInput != '-1': userInput = input('Enter any key to continue or -1 to quit: ') print('Good bye')
The code above should be quite self-explanatory. The output below shows an example of how the loop works:
Enter any key to continue or -1 to quit: w Enter any key to continue or -1 to quit: r Enter any key to continue or -1 to quit: Enter any key to continue or -1 to quit: 0 Enter any key to continue or -1 to quit: 123 Enter any key to continue or -1 to quit: safs Enter any key to continue or -1 to quit: -1 Good bye
Practice Question
Now that we’ve covered all the relevant concepts on using not equal operators in Python, let’s move on to our practice question.
For today’s practice question, we need to write a function called sumNonMultiples()
that has two parameters n
and nums
.
n
is an integer while nums
is a list of integers.
The function should sum all the integers in nums
that are not multiples of n
and return the sum.
For instance, if nums = [2, 3, 4, 5, 6, 7, 8]
and n = 3
, the function should sum 2, 4, 5, 7 and 8 and return the value 2 + 4 + 5 + 7 + 8 = 26.
Expected Results
To test your function, you can run the code below:
nums = [2, 3, 4, 5, 6, 7, 8] print(sumNonMultiples(4, nums)) #returns 2+3+5+6+7 = 23 print(sumNonMultiples(5, nums)) #returns 2+3+4+6+7+8 = 30 print(sumNonMultiples(6, nums)) #returns 2+3+4+5+7+8 = 29
You should get the following output:
23 30 29
Suggested Solution
def sumNonMultiples(n, nums): sum = 0 for i in nums: if i%n != 0: sum += i return sum
In the solution above, we first declare a function called sumNonMultiples()
with two parameters – n
and nums
.
Inside the function, we declare and initialize a variable called sum
to 0.
Next, we use a for
loop to iterate over nums
. For each integer i
in nums
, we check if the remainder when i
is divided by n
is zero.
If it is not, it means i
is not a multiple of n
. Hence, we add i
to sum
.
After iterating over all the elements in nums
, we return the value of sum
.
With that, the function is complete.