Python Equality vs Identity Operator: == vs is

😊❤️ Todays topic: (is vs == in Python) These two look similar, but they check completely different things. == (Equality Operator): Checks if the values are equal a = [1, 2, 3] b = [1, 2, 3] print(a == b) Output: True Explanation: Both lists have the same values, so Python returns True. is (Identity Operator): Checks if both variables refer to the same object in memory a = [1, 2, 3] b = [1, 2, 3] print(a is b) Output: False Explanation: Even though values are same, they are stored in different memory locations. Now see this case: x = 10 y = 10 print(x is y) Output: True Explanation: Python reuses small integers (like -5 to 256), so both variables may point to the same object. Key Difference: == compares values is compares memory location (identity) When to use: Use == when comparing values Use is when checking if two variables refer to the same object (Example: checking None) x = None if x is None: print("No value") Interview Insight: Using is instead of == for value comparison can lead to incorrect results, especially with lists, dictionaries, or large numbers. Quick Question: What will be the output? a = "hello" b = "hello" print(a is b) #Python #Programming #Coding #InterviewPreparation #Developers

Output is True as string is considered small Datatypes by cpython compiler

Like
Reply

is checks for identity, means if the both variable refer to same object in memory location. whereas == checks if values of variables are equal or Not( both return booleans )

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories