Saturday 4 November 2023

Difference between == and = in python

 


x=[1,2,3] ; y=[1,2,3]

x==y      

x is y

In Python, when you use the == operator, it checks if the values of the two variables are equal. So, when you do x == y, it will return True because the values of x and y are the same: both lists contain the same elements in the same order.

However, when you use the is operator, it checks if two variables refer to the same object in memory. In your example, x is y will return False because even though the values of x and y are the same, they are two different list objects in memory. This is because lists are mutable objects in Python, and the x and y variables refer to two separate list objects that happen to have the same values.


x=[1,2,3] ; y=[1,2,3]

x=y     

x is y

In this case, when you do x = y, you are assigning the variable x to refer to the same list object that y is referring to. As a result, x and y now both point to the same list object in memory. So, when you check x is y, it will return True because they are indeed the same object in memory.

Here's what happens step by step:

x and y are initially two separate list objects with the same values: [1, 2, 3].

When you do x = y, you're essentially making x reference the same list object as y. Now, both x and y point to the same list object.

Therefore, when you check x is y, it returns True because they are the same object in memory.

Keep in mind that this behavior is specific to mutable objects like lists in Python. For immutable objects like integers or strings, x is y would return True if x and y have the same value, because Python caches some immutable objects, and they can be shared among variables.

0 Comments:

Post a Comment

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (118) C (77) C# (12) C++ (82) Course (62) Coursera (180) Cybersecurity (22) data management (11) Data Science (95) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (753) Python Coding Challenge (232) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses