The == operator compares the values of both the operands and checks for value equality. Whereas is operator checks whether both the operands ask an equivalent object or not.
[pastacode lang=”python” manual=”%23%20python3%20code%20to%20%20%0A%23%20illustrate%20the%20%20%0A%23%20difference%20between%20%0A%23%20%3D%3D%20and%20is%20operator%20%0A%23%20%5B%5D%20is%20an%20empty%20list%20%0Alist1%20%3D%20%5B%5D%20%0Alist2%20%3D%20%5B%5D%20%0Alist3%3Dlist1%20%0A%20%20%0Aif%20(list1%20%3D%3D%20list2)%3A%20%0A%20%20%20%20print(%22True%22)%20%0Aelse%3A%20%0A%20%20%20%20print(%22False%22)%20%0A%20%20%0Aif%20(list1%20is%20list2)%3A%20%0A%20%20%20%20print(%22True%22)%20%0Aelse%3A%20%0A%20%20%20%20print(%22False%22)%20%0A%20%20%0Aif%20(list1%20is%20list3)%3A%20%0A%20%20%20%20print(%22True%22)%20%0Aelse%3A%20%20%20%20%20%0A%20%20%20%20print(%22False%22)%20″ message=”” highlight=”” provider=”manual”/]OUTPUT :
[pastacode lang=”python” manual=”True%0AFalse%0ATrue” message=”” highlight=”” provider=”manual”/]- Output of the primary if condition is “True” as both list 1 and list 2 are empty lists.
- Second if condition shows “False” because two empty lists are at different memory locations. Hence list 1 and list 2 ask different objects. we will check it with id () function in python which returns the “identity” of an object.
- Output of the third if condition is “True” as both list 1 and list 3 are pointing to an equivalent object.
OUTPUT :
[pastacode lang=”python” manual=”139877155242696%0A139877155253640″ message=”” highlight=”” provider=”manual”/]