Python Not Equal – Does Not Equal Operator Tutorial

When programming in Python, you‘ll often need to check if two values are not equal to each other. This is where the "not equal" operator, represented by the != symbol, comes in handy.

In this tutorial, we‘ll take an in-depth look at how the != operator works in Python. We‘ll see examples of using it to compare various data types, how to use it in control flow statements like if and while, how it compares to the "is not" operator, and some potential edge cases to watch out for.

By the end, you‘ll have a solid understanding of this core programming concept that you can apply in your own Python projects. Let‘s dive in!

What Does the Not Equal Operator Do?

The != operator in Python checks if two values are not equal to each other. If they are different, it returns True. If they are the same, it returns False.

For example:

>>> 2 != 4
True
>>> "hello" != "hello" 
False

This operator works with all the basic data types in Python, including numbers, strings, and booleans, as well as collections like lists, tuples, sets and dictionaries. Essentially, any two objects that can be compared can be tested for inequality using !=.

Checking for inequality is a fundamental part of programming. You‘ll use it all the time for tasks like:

  • Determining if user input is valid
  • Controlling the flow of a program based on certain conditions
  • Iterating through a collection until a sentinel value is reached
  • Filtering a dataset to exclude unwanted values

Now that we understand the basics of what != does, let‘s look at some examples of it in action.

Comparing Basic Types with !=

The != operator can be used with all the basic data types in Python. Here‘s how it works with each one:

Numbers

You can use != to compare any type of number, including integers, floats, and complex numbers:

>>> 10 != 20
True
>>> 3.14 != 2.718 
True 
>>> 2 + 3j != 4 + 5j
True

Strings

Strings can be compared using !=, which checks if two strings have different characters:

>>> "Python" != "python"
True
>>> "Hello world" != "Hello world!"
True 

String comparison is case-sensitive, so uppercase and lowercase characters are considered different.

Booleans

The two boolean values in Python, True and False can be compared using !=:

>>> True != False  
True
>>> False != False
False

Comparing Collections with !=

Python has several built-in collection types that allow you to store multiple values. The != operator also works on these:

Lists

Lists are ordered, mutable sequences. Two lists are considered unequal if they have different lengths, or if any of the elements at the same index are different:

>>> [1, 2, 3] != [1, 2, 3, 4] 
True
>>> [1, 2, 3] != [1, 4, 3]
True

Tuples

Tuples are similar to lists, but they are immutable. The same rules apply for comparing them:

>>> (1, 2, 3) != (1, 2)
True  
>>> (1, 2, 3) != (1, 2, 4)
True

Sets

Sets are unordered collections of unique elements. Two sets are considered unequal if they have different elements, regardless of order:

>>> {1, 2, 3} != {3, 2, 1}
False
>>> {1, 2, 3} != {1, 2, 3, 4}  
True

Dictionaries

Dictionaries are unordered mappings of keys to values. Two dictionaries are considered unequal if they have different keys, or if any of the values for the same key are different:

>>> {"a": 1, "b": 2} != {"b": 2, "a": 1}  
False
>>> {"a": 1, "b": 2} != {"a": 1, "b": 3}
True  

Using != in Control Flow

One of the most common uses of the != operator is in control flow statements like if and while. These allow you to execute different code paths based on whether a condition is true or false.

If Statements

An if statement runs a block of code only if a given condition is true. You can use != to check for inequality in the condition:

x = 10
y = 20

if x != y:
    print("x and y are not equal")
else:
    print("x and y are equal")  

This will print "x and y are not equal", since 10 is not equal to 20.

While Loops

A while loop repeatedly executes a block of code as long as a condition is true. You can use != to specify the condition:

count = 0

while count != 5:
    print(count)
    count += 1

This loop will print the numbers 0 through 4, stopping when count is no longer not equal to 5.

Using != in the condition is a common way to iterate until some sentinel value is reached.

!= vs is not

Python has another operator, is not, which is similar to != but behaves differently in some cases.

The != operator compares the values of two objects, while is not compares their identities – that is, whether they are the exact same object in memory.

For immutable types like numbers, strings, and tuples, there‘s effectively no difference between the two:

>>> 2 != 3
True
>>> 2 is not 3
True

But for mutable types like lists, sets, and dictionaries, it‘s possible for two objects to be considered equal by value but not by identity:

>>> [1, 2] != [1, 2]   
False
>>> [1, 2] is not [1, 2]
True 

Here, the two lists have the same elements, so they are considered equal. But they are two different list objects in memory, so they are not identical.

In general, you should use != for comparing values and is not for comparing identities. Use is not when you need to know if two variables refer to the exact same object.

Comparing to None

None is a special constant in Python that represents the absence of a value. It‘s often used to initialize variables or as a default return value for functions.

To check if a variable is None, you should use the is operator rather than ==. This is because None is a singleton object, so there is only ever one instance of it:

x = None

if x is None:
    print("x is None")

Using != None will work, but is not as clear and can be less efficient:

if x != None:
    print("x is not None") 

So when dealing with None, always prefer using is or is not for comparisons.

Chaining Multiple != Comparisons

You can use the != operator multiple times in the same expression to check for multiple inequalities at once.

For example, suppose you want to check if a variable x is not equal to any of 2, 4, or 6. You could do it like this:

if x != 2 and x != 4 and x != 6:
    print("x is not 2, 4, or 6") 

But Python provides a more concise way using chained comparisons:

if 2 != x != 4 != 6:
    print("x is not 2, 4, or 6")

This is equivalent to the previous version, but more compact and readable. It checks if each comparison in the chain is true – in this case, if 2 != x, x != 4, and 4 != 6.

You can chain as many comparisons as you want in this way, mixing different operators:

if 0 < x <= 10 != 5:
    print("x is between 0 and 10, but not 5")

This is a handy way to express complex conditions involving multiple values and inequalities.

Potential Gotchas

While the != operator is generally straightforward, there are a couple potential gotchas to be aware of.

Floating Point Precision

When comparing floating point numbers, you need to be careful about precision issues. Because of the way floats are represented internally, two numbers that look the same may actually be slightly different.

For example:

>>> 0.1 + 0.2 == 0.3
False

The sum 0.1 + 0.2 should mathematically equal 0.3, but it‘s actually slightly off in the least significant bits. This is a well-known problem with floating point arithmetic.

For this reason, it‘s generally not a good idea to use != (or ==) to compare floats directly. Instead, check if the absolute difference between them is less than some small tolerance value:

tolerance = 1e-6
if abs((0.1 + 0.2) - 0.3) < tolerance:
    print("Close enough")  

Mutable vs Immutable Types

As we saw in the section on != vs is not, mutable and immutable types behave differently when compared.

Immutable types like numbers, strings, and tuples can be easily compared with !=, since their values can‘t change after creation.

But mutable types like lists, sets, and dictionaries can be modified in place. This means two variables can start out pointing to equal objects, but then become different if one of them is modified:

a = [1, 2]
b = [1, 2]  

if a != b:
    print("a and b are not equal")
else:
    print("a and b are equal")

a.append(3)

if a != b:  
    print("a and b are no longer equal")

Here, a and b start out as equal lists. But after modifying a, they are no longer equal. This is something to watch out for when comparing mutable objects – make sure you‘re comparing them at the right point in your code, after any potential modifications.

Conclusion

In this tutorial, we took a deep dive into the != "not equal" operator in Python. We saw how to use it to compare different data types, how to incorporate it into if statements and while loops, how it differs from the is not operator, and some potential issues to be aware of.

Checking for inequality is a fundamental part of programming logic, and the != operator is the main way to do it in Python. Understanding how it works with different types, and how to use it effectively in your code, is an important skill for any Python developer.

I hope this article helped solidify your understanding of this core concept. Now you‘re ready to use != in your own projects with confidence!

Similar Posts