educative.io

Educative

Comparision Operators, Python

num2 = 10
num3 = 10
list1 = [6,7,8]
list2 = [6,7,8]

print(num2 is not num3) # Both have the same object
print(list1 is list2) # Both have the different objects

OUTPUT: false
false

It shows false in both the print cases. I am not able to understand regarding the objects which has been mentioned in the comment part for explaining this output . Please elaborate the reason, how both the print cases are different in terms of object.
And also please clarify list1 = [6,7,8] & list2 = [6,7,8] are equal or not? I think if the order of the elements are different then the lists are said to be unequal otherwise if the order is same then it is said equal.

Type your question above this line.

Course: https://www.educative.io/collection/10370001/5473789393502208
Lesson: https://www.educative.io/collection/page/10370001/5473789393502208/5429296082452480

Hi @GIRIBALA_MAHANTO ,
Here, we see that num1 and num2 are integers of the same values, so they are equal as well as identical.

But list1 and list2 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory although they are equal.

1 Like

Hi @Ammar_Ahmad_Farid
If I am not wrong, are you saying that num1 and num2 point to same memory location , hence identical?

Both num1 and num2 have the same id’s while lists don’t have. You can check by running the below code.

num1=10

num2=10

print(id(num1)) #4303493760

print(id(num2)) #4303493760

list1 = [6,7,8]

list2 = [6,7,8]

print(id(list1)) #140598573294080

print(id(list2)) #140598841828800

The id() function returns a unique id for the specified object . All objects in Python has its own unique id. The id is assigned to the object when it is created.

Mutable objects are not same in Python.

3 Likes

So glad someone asked this question already. I still have questions about how these IDs get assigned. Why is it that the lists have different IDs but these strings have the same ID?

list1 = [6,7,8]
list2 = [6,7,8]
string1 = "Hello, World!"
string2 = "Hello, World!"

print(list1 is list2) # Both have the different objects
print(list1 == list2)

print(string1 is string2)
print(string1 == string2)

print(id(string1))
print(id(string2))

Yields:

False
True

True
True

139694609046024
139694609046024


Course: Learn Python 3 from Scratch - Free Interactive Course
Lesson: Comparison Operators - Learn Python 3 from Scratch