I’m learning Python with version 3.2 at the moment.
Given two list variables, how do you distinguish if the variables reference the same list vs two separate lists with the same values.
For example:
>>> foo = [1,2,3,4]
>>> bar = foo
>>> foo.append(5)
>>> foo
[1, 2, 3, 4, 5]
>>> bar
[1, 2, 3, 4, 5]
>>> foo == bar
True
In the above, “foo” and “bar” are clearly referencing the same list. (as evidenced by appending “5” to foo and seeing that change reflected in bar as well).
Now, let’s define a third list, called “other” with the same values:
>>> other = [1,2,3,4,5]
>>> other == foo
True
They definitely look like the same list given the comparison operator here also returns True. But if we modify “other”, we can see that it is a different list where changes in either variable don’t impact the other.
>>> other.append(6)
>>> other == foo
False
>>> other
[1, 2, 3, 4, 5, 6]
>>> foo
[1, 2, 3, 4, 5]
I think it would be useful to know when two variables are aliases for each other vs. being identical in structure. But I suspect I might be misunderstanding something else fundamental to the language.
You can use the
isoperator to determine object identity:To quote the documentation:
Another way to detect if two variables refer to the same object (such as a list) is to check te return value of the
id()function: