The following addresses that and related issues.
Let’s consider the difference between identity and equivalence in Python.
In Python, objects are identical if they are, in fact, the same object.
Objects are considered to be equivalent if they have the same value. There are some minor exceptions that recognize equivalence of values that are similar, but not of the same type. See the end of this post for an example.
If objects are identical, they are also equivalent. However, if they are equivalent, they are not necessarily also identical. The following may help clarify the difference between identity and equivalence regarding Python lists.
To help with the discussion, we will be using the following operators:
Let’s create two lists with the same content. They will be equivalent, but not identical.
>>> a = [1, 2, 3, 4, 5, 6, 7] >>> b = [1, 2, 3, 4, 5, 6, 7] >>> a == b # are they equivalent? True >>> a is b # are they identical? False
With lists, the
= operator assigns a reference to the list specified by the expression on the right side of the operator to a variable on the left side of the operator. Let’s demonstrate that by creating a list, assigning it to
c, then assigning
d. This will create only one list, Both
d will refer to that same list. Therefore,
d will be identical and also equivalent.
>>> c = [1, 2, 3, 4, 5, 6, 7] >>> d = c >>> c == d True >>> c is d True
Taking a slice of a list creates a new list. We can use this as a means of making a copy of a list. Let’s try that with two variables,
>>> e = [1, 2, 3, 4, 5, 6, 7] >>> f = e[:] # this slice includes all of the elements in e >>> e == f True >>> e is f False
b are equivalent, but not identical. Let’s modify
a and find out whether that affects
>>> a.append(8) # 8 gets appended to a, but not to b >>> a [1, 2, 3, 4, 5, 6, 7, 8] >>> b [1, 2, 3, 4, 5, 6, 7]
b was not affected.
d are identical. Let’s modify
c and find out whether that affects
>>> c.append(8) # 8 gets appended to c, which affects d >>> c [1, 2, 3, 4, 5, 6, 7, 8] >>> d [1, 2, 3, 4, 5, 6, 7, 8]
d, because both variables refer to the same list.
When a list is passed to a function as an argument, the corresponding function parameter will refer to the same list as the argument. If we wish to work with a copy of the list instead of with the original, we must make a copy of the list. Within the above examples, we used a slice to assign a copy of
f. Alternatively, we could have used the
list function to create the copy, as follows:
>>> f = list(e) >>> e == f True >>> e is f False
As promised above, here is an equivalence between lists that contain items that differ in type:
>>> [1.0, 0.0, 1.0] == [True, False, True] True
Edited on September 6, 2019 to modify the final example