Identity

Introduction:

  • Identity operators in Python are used to compare objects, not if they are equal, but if they are actually the same object with the same memory location.

Types of Identity Operators:

  1. is:
    • The is operator checks if two variables refer to the same object.
    • Syntax: x is y
    • Example:

      python
      x = ["apple", "banana", "cherry"]
      y = x
      z = ["apple", "banana", "cherry"]
      
      print(x is y)  
      print(x is z)  
      • Output: True
      • Output: False
  2. is not:
    • The is not operator checks if two variables do not refer to the same object.
    • Syntax: x is not y
    • Example:

      python
      x = ["apple", "banana", "cherry"]
      y = ["apple", "banana", "cherry"]
      
      print(x is not y)  
      • Output: True
      • Output: True

Detailed Tutorials:

  • Below are tutorials covering each of the identity operators with syntax and examples:
  1. is:
    • The is operator is used to check if two variables refer to the same object.
    • Example:

      python
      a = [1, 2, 3]
      b = a
      c = [1, 2, 3]
      
      print(a is b)  
      print(a is c)  
      • Output: True
      • Output: False
  2. is not:
    • The is not operator is used to check if two variables do not refer to the same object.
    • Example:

      python
      a = [1, 2, 3]
      b = [1, 2, 3]
      
      print(a is not b)  
      • Output: True
      • Output: True

Exercises:

  1. Check Identity:
    • Write a program to check if two lists refer to the same object.

      python
      list1 = [10, 20, 30]
      list2 = list1
      list3 = [10, 20, 30]
      
      print(list1 is list2)  
      print(list1 is list3)  
      • Output: True
      • Output: False
  2. Check Non-Identity:
    • Write a program to check if two strings do not refer to the same object.

      python
      str1 = "hello"
      str2 = "hello"
      str3 = str1
      
      print(str1 is not str2)  
      print(str1 is not str3)  
      • Output: False
      • Output: False

Summary:

  • Identity operators are useful for checking if two variables refer to the same object in memory. Practice using the is and is not operators to understand their behavior and importance in Python!