Python object not equal

How to Compare Objects in Python

In Python, the identity operators ( is and is not) and the equality operators ( == and != ) have a small difference between them. You would have experienced unexpected behavior while using the is or is not operators to compare values. In Python, the is and is not operators are used to check if two objects share the same memory location and the == and != operators are used to compare their values. .

In this tutorial, we will discuss the differences between equality operators and identity operators and when to use them. We will also see what leads to an unexpected behavior when we use the is or is not objects.

You can skip to any specific section of this tutorial on how to compare objects in Python using the table of contents below.

Equality Operators Vs Identity Operators

As we mentioned in the earlier tutorial, everything in Python is an object and has a specific memory location associated. The is and is not operators in Python check if two objects share the same memory location. Note that two objects with the same value will not share the same memory location. The identity of an object can be checked using the id().

Читайте также:  Html обязательные мета теги

In cPython, some objects that have the same value have the same id. The commonly-used integers form – 5 to 256 are interned in cPython. That is, each number in this range occupies a fixed and singular place in the memory.

The sys.intern() can be used to compare the memory addresses instead of comparing each character.

from sys import intern a = "sample" b = "sample" a is b print (id(a)) print (id(b)) a = intern(a) b = intern(b) a is b print (id(a)) print (id(b))
47183403408368 47183402865976 7183403408368 7183403408368

Initially, the memory address of both the variables are pointing to a different location. However, the intern function ensures that they are referring to the same variable.

Comparing Objects Using Equality and Identity Operators

Now, let us see an example where we will use both the is operator and the == operator to understand the difference between both these operators.

data1 = [] data2 = [] data3=data1 if (data1 == data2): print("True") else: print("False") if (data1 is data2): print("True") else: print("False") if (data1 is data3): print("True") else: print("False") data3 = data3 + data2 if (data1 is data3): print("True") else: print("False")

The output of the above code will be as follows:

This is true. This is false. This is true. This is false.
  • In the first if condition, the value of both the lists data1 and data2 are being compared. Both the lists data1 and data2 are empty lists. Therefore, the first if condition gives the output as TRUE.
  • In the second if condition, the memory locations of data1 and data2 are compared. Hence, the output of the if condition is FALSE.
  • Now, data3 and data1 share the same object memory. As a result, the third if condition will be TRUE.
  • Since the two lists are concatenated, it will create a new list. Therefore, the fourth if condition will be FALSE.

Now let us look at the != operator and the is not operator. != is defined as the not equal to operator. If the operands on either side of an expression are of the same value, the != operator will return the output as FALSE and they are of different value, the output will be TRUE.

Let’s see this below example.

a = 120+2 b = 122 if (a != b): print("Not equal") else: print("Eqaual") if ("computer" != "comp"): print("Both are different") else: print("Both are same")

The output of the above code will be as follows:

Let’s now look at the is not operator. Like the is operator, the is not operator compares the memory location of the two objects. It checks the id() of the objects being compared and returns FALSE if they are same. If they are different, it returns TRUE.

x=10 y=x print (id(x)) print (id(y)) if (x is not y): print("Memory location not same") else: print("Memory location same") x=10 y=20 print (id(x)) print (id(y)) if (x is not y): print("Memory location not same") else: print("Memory location")
94383631757216 94383631757216 Memory location same 94383631757216 94383631757536 Memory location not same

The first if statement compares if the memory location of x and y are same or different. From the output, it is clear that both x and y share the same memory location. Then, x and y are assigned two different memory locations. This is confirmed from the output of the second if statement.

Using the Right Operators

Now that we have understood the difference between the == and != operators and the is and is not operators, respectively let us understand when we should use these two operators.

As a standard rule, except when comparing to None , use the == and != operators to compare values. When you want to compare if two values are equal, use the == and != operators. Here, you are not concerned about the memory location of the variables. You only want to check if the content in both these variables are the same.

Comparing Object Identity

If you want to compare the identity of two objects, that is if they are stored in the same memory location, use the is and is not operators. These operators are very useful in comparing variables to None and are preferred over class methods while comparing variables to None.

In this tutorial we have learnt that we can compare the object location of two objects using the identity operators and we can use the equality operators to compare the value of two Python objects. We also saw few examples of these operator types. The tutorial also explained when to use the identity and equality operators. This should help you in preventing the unexpected behavior in your code when you compare two objects.

If you enjoyed this article, be sure to join my Developer Monthly newsletter, where I send out the latest news from the world of Python and JavaScript:

Источник

How to Use Python Not Equal and Equal Operators

python hosting

Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

In Python, you can use the not equal to and the equal to operators to check if two Python objects have the same value. This tutorial will teach you how to use these operators with lots of example code.

In this tutorial you’ll learn:

  • the syntax of the not equal ( != ) operator and use cases,
  • the syntax of the equal operator ( == ) with examples, and
  • the use of is and is not operators to check for the identity of any two Python objects.

Python Not Equal Operator Syntax

For any two Python objects obj1 and obj2 , the general syntax to use the not equal operator is:

  • returns True when the values of obj1 and obj2 are not equal, and
  • returns False otherwise.

Note: As mentioned above, obj1 and obj2 can be integers, floating point numbers, strings, lists and so on.

Python Not Equal Operator Code Examples

In this section, let’s code a few examples to understand the not equal operator better.

Using Python Not Equal Operator for Comparison

num1 = 27 num2 = 3*9 num1 != num2 # Output: False

You can run the code examples on the Geekflare Python IDE—right from your browser. Or you could choose to run on your local machine.

As num1 = 27 , and num2 also evaluates to 27 ( 3*9 = 27 ), the values of num1 and num2 are equal. So the != operator returns False .

Let’s take another example.

In the code below, num1 is set to 7. And num2 is set to the string 7. As they’re of different data types, the not equal operator returns True .

num1 = 7 num2 = "7" num1 != num2 # Output: True

You cast the string to an integer, as shown:

num1 = 7 num2 = int("7") num1 != num2 # Output: False

In this case, you can see that the returned result is False —as num1 and num2 are now equal to the integer 7.

You can also use the not equal operator with Python collections such as lists, tuples, and sets.

Note: For collections of data such as lists, the not equal operator works by checking the values of individual items. For example, two lists list1 and list2 —each of length n —are equal only if list1[i] == list2[i] for i in .

list1 = [2,4,6,8] list2 = [2,4,6,9] list1 != list2 # Output: True

In the above example, list1 and list2 differ by only one element. And the not equal != operator returns True as expected.

Using Python Not Equal Operator in Conditionals

You’ll often use the not equal to operator as part of Python conditionals.

For example, the code snippet below shows how you can you can check whether or not a number is odd.

A number that is not evenly divisible by 2 is odd. And this reduces to the condition num%2 != 0 .

num = 7 if(num%2 != 0): print("The number is odd.") else: print("The number is even.") # Output: The number is odd.

You can also use conditionals in list comprehensions when you want to retain only those list elements that meet a specific condition. In the example below, odd_10 is the list of all odd numbers less than 10.

odd = [num for num in range(10) if num%2 != 0] print(odd) # Output: [1, 3, 5, 7, 9]

And that completes our discussion of the not equal ( != ) operator.✅

As you might have guessed by now the equal to operator produces the opposite effect of of the not equal to operator.

You’ll learn more about it in the next section.

Python Equal Operator Syntax

Here’s the syntax to use Python’s equal to operator:

 == #where and are valid Python objects

Python Equal Operator Code Examples

The equal operator ( == ) can be used very similarly to the not equal operator.

Let’s code the following examples:

  • to check if two strings are equal,
  • to check if a number is even, and
  • to use conditionals in list comprehension

Using Python Not Equal Operator for Comparison

In the code snippet below, str1 and str2 are equal in terms of value. So the equal operator ( == ) returns True .

str1 = "coding" str2 = "coding" str1 == str2 # Output: True

python-equals-operator

Let’s now use the equal operator in a conditional expression.

Note: A number that is evenly divisible by 2 is even. And in code, this reduces to the condition num%2 == 0

num = 10 if(num%2 == 0): print("The number is even.") else: print("The number is odd.") # Output: The number is even. 

Let’s now build on this example, use Python’s list comprehension to get all even numbers less than 10.

even_10 = [num for num in range(10) if num%2 == 0] print(even_10) # Output: [0, 2, 4, 6, 8]
  • range(10) returns a range object which can be looped through to get all integers from 0 to 9.
  • The condition num%2 == 0 is True only for even numbers.
  • So even_10 is the list of all even numbers less than 10.

So far you’ve learned how to to check for equality using the not equal ( != ) and equal ( == ) operators.

In the next section, you’ll learn how to verify the identity of two objects. You’ll check if two Python objects are identical.

How to Use Python’s is and is not Operators

If you are a beginner in Python programming, it’s possible that you’re confused between the == and is operators. Let’s clarify that in this section.

In the previous section, we had an example where str1 and str2 where equal and the == operator returned True .

Now run the following code snippet.

str1 = "coding" str2 = "coding" str1 is str2 # Output: False

You can see that str1 is str2 returns False .

Let’s take a step back and understand what Python’s is operator does.

The is operator operates on on any two Python objects.
And returns True only if the two objects are identical—that is they refer to the same object in memory.

Even though str1 is equal to str2 , str1 is not str2 as they point to two different objects in memory. And therefore, they have different identities.

python-is-operator

In Python, you can use the id() function to get the identity of the object.

▶ Run the following code cell to get the identities of str1 and str2 .

id(str1) # Sample output: 139935398870320 id(str2) # Sample output: 139935398871344

As you can see, str1 and str2 have different identities. And str1 is str2 returns False as expected.

 is # returns True if and only if id() == id() # returns True

Let’s quickly verify this, as shown:

str1 = "coding" str2 = str1 print(str1 is str2) print(id(str1) == id(str2)) # Output True True

Intuitively, the is not operator does the opposite of the is operator.

The is not operator operates on on any two Python objects.
And returns False only if the two objects are identical—that is they refer to the same object in memory. Otherwise, it returns True .

In the above code examples, try replacing is with is not and check the results.

Conclusion 👩‍💻

Hope you found this tutorial helpful.

To summarize, you’ve learned:

  • how to use the equal ( == ) and not equal ( != ) operators to check if two Python objects have the same value,
  • the difference between equality and identity of Python objects, and
  • how Python’s is and is not operators help in checking if two Python objects are identical.

See you all in the next tutorial. Until then, happy learning and coding!🎉

Источник

Оцените статью