Search⌘ K
AI Features

How Operators Treat the Variables?

Explore how Python handles variable assignments through references versus copies, and understand the distinct purposes of the == and is operators for equality and identity checks. This lesson clarifies how operators interact with variables and objects in Python.

This section addresses two common questions, and coding without knowing the answers to them is like skating on thin ice. Without any further delay, let’s explore them together.

Holding references or copies

We must know the difference between holding a reference to an item and holding a copy of an item. For example, if we have two variables x and y:

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

The line y = x means that y holds the reference to the same list as x. Tweaking x as:

x.append(4)

will also affect the variable y. Run the following program to witness this change.

Python 3.10.4
x = [1, 2, 3]
y = x
x.append(4) # Tweaking variable x
print(y) # Witnessing change in the other variable

Are variables boxes?

Now try answering this question: are variables boxes? If we take variables as boxes, then the assignment (=) won’t make any sense. Let’s visualize this concept.

If we treat x and y as separate boxes, changing x would never reflect a diversification in variable y. Similarly, changing y won’t modify x. So, we can clearly state that variables are not boxes, and that two variables hold a reference to the same item (instead of a copy) when assigned to each other.

This whole discussion brings us to a very crucial concept in Python, that is the difference between the == and the is operator.

== versus is

The == operator compares by checking equality. Whereas, the is operator compares identities. For example, if we have two variables x and y as:

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

Here, the question is: what will x == y and x is y will evaluate to? x == y will return True because both lists look the same. This doesn’t assure that both variables point to the same object. To verify whether both variables hold a reference to the same object, use the is operator. In this case, x is y will also be True because they both are pointing to one list object. Run the program to witness it.

Python 3.10.4
x = [1, 2, 3]
y = x
print(x == y)
print(x is y)

Let’s see another case, as follows:

x = [1, 2, 3]
y = list(x)

Here, x == y will return True because both lists look the same. Whereas, x is y will be False because they both are pointing to different objects. Let’s run it.

Python 3.10.4
x = [1, 2, 3]
y = list(x)
print(x == y)
print(x is y)

✏️ Note: To get an overview of how different operators work in Python, check out this shot.