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

100 Python Programs for Beginner (59) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (174) C (77) C# (12) C++ (82) Course (67) Coursera (228) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (60) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (939) Python Coding Challenge (373) Python Quiz (31) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

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