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:
- is:
- The
isoperator checks if two variables refer to the same object. - Syntax:
x is y Example:
pythonx = ["apple", "banana", "cherry"] y = x z = ["apple", "banana", "cherry"] print(x is y) print(x is z)- Output:
True - Output:
False
- Output:
- The
- is not:
- The
is notoperator checks if two variables do not refer to the same object. - Syntax:
x is not y Example:
pythonx = ["apple", "banana", "cherry"] y = ["apple", "banana", "cherry"] print(x is not y)- Output:
True - Output:
True
- Output:
- The
Detailed Tutorials:
- Below are tutorials covering each of the identity operators with syntax and examples:
- is:
- The
isoperator is used to check if two variables refer to the same object. Example:
pythona = [1, 2, 3] b = a c = [1, 2, 3] print(a is b) print(a is c)- Output:
True - Output:
False
- Output:
- The
- is not:
- The
is notoperator is used to check if two variables do not refer to the same object. Example:
pythona = [1, 2, 3] b = [1, 2, 3] print(a is not b)- Output:
True - Output:
True
- Output:
- The
Exercises:
- Check Identity:
Write a program to check if two lists refer to the same object.
pythonlist1 = [10, 20, 30] list2 = list1 list3 = [10, 20, 30] print(list1 is list2) print(list1 is list3)- Output:
True - Output:
False
- Output:
- Check Non-Identity:
Write a program to check if two strings do not refer to the same object.
pythonstr1 = "hello" str2 = "hello" str3 = str1 print(str1 is not str2) print(str1 is not str3)- Output:
False - Output:
False
- Output:
Summary:
- Identity operators are useful for checking if two variables refer to the same object in memory. Practice using the
isandis notoperators to understand their behavior and importance in Python!