Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing lists by reference vs value in Python

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.

like image 649
selbie Avatar asked Dec 29 '12 10:12

selbie


1 Answers

You can use the is operator to determine object identity:

>>> foo is bar
True
>>> foo is other
False

To quote the documentation:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.

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:

>>> id(foo)
4432316608
>>> id(bar)
4432316608
>>> id(other)
4432420232
like image 63
Martijn Pieters Avatar answered Nov 14 '22 22:11

Martijn Pieters