How do you check if a variable references another declared object in Python?


Printing type of one variable just returns the pointed data’s type

i = [5,6,7,8]
j = i
<class 'list'>

and j references a mutable type. So

j[0] = 3
[3, 6, 7, 8]
[3, 6, 7, 8]

I want a function that returns true for j and false for i. If it’s built-in or anyone could write that it would be appreciated.

Asked By: Timothy Oh



Python doesn’t have pointers. All variables act as references to objects. There is no "pointer" type.


So, you’ve changed your question to ask:

How do you check if a variable references another declared variable in

But again, all variables act as references to objects. Variables don’t reference other variables. They reference objects. In this case, they reference the same object. You can check that by using:

i is j
Answered By: juanpa.arrivillaga

There’s no ‘pointers’ in Python, like there are in C++ (or similar languages). The only distinction in Python is mutable vs. immutable. But all variables are just references to objects.

Variables with immutable types refer to values that you cannot modify, only replace. int is an example of an immutable type.

When you run your code, you assign 5 to i, then you assign the value of i to j, so that j now also has the value 5, but since these are immutable values, you can only change the entire value of either variable, which won’t affect the value of the other.

Variables with mutable types have values that you can modify. list is an example of a mutable type.

When you run this:

xs = [1, 2, 3]
ys = xs
xs[0] = 999

The last statement modifies the value of both variables, as the list that was the value of xs is the same list that was assigned to ys and the final instruction modifies that value.

Immutable types including numbers, strings and tuples as well as a few other simple types. Mutable types include lists, dictionaries, and most other more complex classes.

Also, for example have a look at this:

a = 1
b = 1
c = b + 1
d = 2
print(id(a), id(b), id(c), id(d))

This will print four numbers, but note how the first two numbers will be the same (as they both refer to 1) and the second two are the same as well (as they both refer to 2).

Having said all that, if you want to test if something is mutable, there’s no easy way to do that – but a common reason to want to do so is because you want to test if something is hashable, which you could test:

s = 'test'
print(s.__hash__ is None)  # False

xs = [1, 2, 3]
print(xs.__hash__ is None)  # True
Answered By: Grismar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.