in

How to Use Python Not Equal and Equal Operators

default image

Equality and inequality operators are essential in Python programming. They allow you to compare values and check conditions.

In this comprehensive guide, you‘ll learn:

  • The syntax and use cases for Python‘s not equal (!=) and equal (==) operators
  • How to use != and == to compare numbers, strings, lists, and other objects
  • Examples of using these operators in if statements and loops
  • The difference between == and Python‘s is operator
  • When to use != vs is not and == vs is

By the end of this tutorial, you‘ll be proficient in leveraging != and == operators in your Python code. Let‘s dive in!

The Not Equal (!=) Operator in Python

The not equal operator (!=) compares two values and evaluates to True if they are not equal. The syntax is:

value1 != value2

If value1 and value2 are not equal, != returns True. Otherwise, it returns False.

Some examples:

5 != 10  # True, 5 does not equal 10

"hello" != "Hello"  # True, string case matters

[1,2] != [1,2] # False, the lists contain the same elements

You can use != to compare all Python data types – numbers, booleans, strings, lists, tuples, dicts, and more. The values must match exactly, including identical types, for != to return False.

Let‘s look at more examples of using the not equal operator.

Comparing Numbers

When comparing numbers, != checks if the values are exactly equal.

num1 = 5
num2 = 10

print(num1 != num2) # True

It also works with float values:

x = 3.14159
y = 2.71828

print(x != y) # True

And you can compare variables against hardcoded values:

a = 10

print(a != 20) # True 
print(a != 10) # False

Comparing Strings

For strings, != checks if every character matches exactly, including capitalization:

name1 = "Mark" 
name2 = "mark"

print(name1 != name2) # True, case matters

You can also compare substrings:

full_name = "Mark Smith"

print(full_name != "Mark") # True
print(full_name != "John") # True

And string variables against hardcoded strings:

first_name = "John"

print(first_name != "john") # True 
print(first_name != "John") # False

Comparing Python Collections

You can also use != to compare lists, tuples, dictionaries, and sets. != will return True if any elements in the collections do not match.

For example:

fruits1 = ["orange", "apple", "banana"]
fruits2 = ["apple", "banana", "cherry"] 

print(fruits1 != fruits2) # True, lists are not equal

This also works for tuples:

point1 = (1, 2)  
point2 = (1, 3)

print(point1 != point2) # True, tuples are not equal

And dictionaries if they don‘t have the same keys and values:

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 2, "a": 1} 

print(dict1 != dict2) # False, dictionaries are equal 

dict2["c"] = 3

print(dict1 != dict2) # True, dictionaries are not equal

So in summary, != lets you easily compare just about any two Python objects.

Next let‘s look at how to use the != operator in conditionals and loops.

Using != in Conditionals and Loops

You‘ll often use != in conditional statements like if/else to control program flow based on inequality:

password = "topsecret"
user_input = input("Please enter the password: ")

if user_input != password:
  print("Incorrect password!")
else:
  print("Password match, access granted") 

This checks if the user‘s input is not equal to the password, printing a response.

Another example is using != to check for invalid numbers in a loop:

while True:
  value = float(input("Please enter a number above 0: "))
  if value != value or value < 0: 
    print("Invalid number, try again")
    continue
  print("Number entered:", value)
  break # exits loop

This loops continuously until a valid number over 0 is entered.

You can also use != in list comprehensions. For example, to filter a list:

numbers = [1, 2, 3, 4, 5, 6]

evens = [n for n in numbers if n != 3]
# evens = [1, 2, 4, 5, 6] 

This creates a new list excluding the value 3.

As you can see, != gives you flexibility in controlling program flow and filtering data.

The Equal (==) Operator in Python

The equal operator (==) compares two values and evaluates to True if they are equivalent. The syntax is:

value1 == value2 

If value1 and value2 are equal, == returns True. Otherwise, it returns False.

Some examples:

5 == 5 # True

"hello" == "hello" # True

[1,2] == [1,2] # True 

5 == 10 # False

"hello" == "Hello" # False

== works with all Python data types like !=. The values must match exactly, including type, to return True.

Now let‘s look at more examples of using the equal operator.

Comparing Numbers

You can use == to check if numeric values or variables are equal:

x = 10
y = 10.0

print(x == y) # True

a = 5
b = 4

print(a == b) # False

This works for integers, floats, and complex numbers.

Comparing Strings

For strings, == will return True if the sequences of characters are identical:

s1 = "Python"
s2 = "Python"

print(s1 == s2) # True

But == considers case:

s3 = "python"

print(s1 == s3) # False, case matters

You can also compare substrings:

full_name = "Mark Smith"

print(full_name == "Mark Smith") # True
print(full_name == "Mark") # False

Comparing Python Collections

== works with Python collections like lists, tuples, dicts, and sets as well. The collections must contain the same elements in the same order to be considered equal.

For example:

l1 = [1,2,3]
l2 = [1,2,3]

print(l1 == l2) # True

t1 = (1,2,3)
t2 = (3,2,1) 

print(t1 == t2) # False, order matters

And dictionaries with string keys:

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 2, "a": 1}

print(dict1 == dict2) # True, same keys & values

So == works intuitively with collections in Python.

Using == in Conditionals and Loops

Much like !=, you‘ll often use == in conditionals like if statements:

age = 25
adult_age = 18

if age == adult_age:
  print("You are officially an adult!")
elif age > adult_age:
  print("You are over 18")
else:
  print("You are under 18")

This checks for equality to 18 and responds appropriately.

And == can be used in loops:

pin = 12345

while True:
  user_pin = int(input("Please enter your PIN: "))
  if user_pin == pin:
    print("PIN accepted!")
    break
  else:
    print("Invalid PIN, try again")

Here we continuously prompt for a valid PIN.

== is also useful in list comprehensions for filtering:

grades = [92, 85, 70, 90, 87]

passing = [g for g in grades if g == 90]
# passing = [90]

This filters the list to only 90 values.

So == gives you another tool for controlling program flow and filtering data.

Comparing == and is in Python

Python has two ways to check for equality:

  • == tests if two values are equivalent
  • is checks if two references point to the same object

The == operator checks if the values or contents of two objects are the same. The is operator checks if the actual objects themselves are identical.

For example:

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

print(a == b) # True, lists contain the same elements
print(a is b) # False, lists are distinct objects

Here a and b are equal, but they are not the same list object in memory.

The is operator is faster than ==, but less flexible:

c = [1,2,3]  
d = c

print(c == d) # True, equal values
print(c is d) # True, c and d reference the same list

Now c and d point to the same underlying list. So they are identical (is) as well as equal (==).

Some key differences:

  • Use == to compare str and int literals (since they get created separately).
  • Use is to check if two variables reference the same object.
  • == checks the values. is checks object identity.

In summary:

  • == tests equality of value
  • is tests identity of the object

Comparing != and is not in Python

There are also two ways to check for inequality in Python:

  • != checks if two values are not equal
  • is not checks if two references do not point to the same object

The != operator checks for value inequality, while is not checks for non-identity.

For example:

a = [1,2,3]
b = [4,5,6]

print(a != b) # True, list values differ
print(a is not b) # True, a and b reference different objects

Here both != and is not will return True.

But you can have inequality without non-identity:

c = [1,2,3]
d = [1,2,3] 

print(c != d) # False, lists contain the same values
print(c is not d) # True, distinct objects in memory

So in summary:

  • != checks inequality of value
  • is not checks non-identity of the object

Summary

To wrap up:

  • The != operator compares two values and returns True if they are not equal. Use != to test for inequality.

  • The == operator compares two values and returns True if they are equal. Use == to test for equality.

  • The is operator checks if two references point to the same object. Use is to test identity.

  • The != and is operators have similar counterparts: != tests inequality, while is not tests non-identity.

  • In conditionals and loops, use != and == to control program flow and comparisons.

  • != and == work for all Python data types like numbers, strings, lists, and dicts.

By mastering these operators, you can write cleaner Python code and have greater control over program logic. Thanks for reading!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.