[Tutor] lists, name semantics

Ben Finney ben+python at benfinney.id.au
Sat Apr 18 05:51:05 CEST 2015


Ben Finney <ben+python at benfinney.id.au> writes:

> Bill Allen <wallenpb at gmail.com> writes:
>
> > If I have a list defined as my_list = ['a','b','c'], what is the is
> > differnce between refering to it as my_list or my_list[:]?
>
> ‘my_list’ is a reference to the object you've already described (the
> existing object ‘['a', 'b', 'c']’).
>
> ‘my_list[:]’ is an operation that takes the original object and
> creates a new one by slicing. In this case, the new object happens to
> be equal to (but probably not identical to) the original, because of
> the slice you specified.

To demonstrate how identity differs from equality, use the appropriate
comparison operators::

    $ python3

    >>> foo = ['a', 'b', 'c']

    >>> bar = foo     # Bind the name ‘bar’ to the same object.
    >>> bar           # Show me the object referred to by ‘bar’.
    ['a', 'b', 'c']
    >>> bar == foo    # Is the object ‘bar’ equal to the object ‘foo’?
    True
    >>> bar is foo    # Is ‘bar’ referring to the same object as ‘foo’?
    True

    >>> baz = foo[:]  # Slice ‘foo’, creating a new list; bind ‘baz’ to that.
    >>> baz           # Show me the object referred to by ‘baz’.
    ['a', 'b', 'c']
    >>> baz == foo    # Is the object ‘baz’ equal to the object ‘foo’?
    True
    >>> baz is foo    # Is ‘baz’ referring to the same object as ‘foo’?
    False

References which compare identical *are the same* object, guaranteed.
Object identity almost always implies equality.

(“almost always” because some object types have unusual behaviour like
“the object is not equal to itself”. Don't fret about that though, these
exceptions are clearly defined when you find them.)


References which compare equal *may under some conditions* be identical.
This is *not* ever a promise, though, and you should never rely on it,
not even in the same session of a program.

Some of Python's internal optimisations depend on the fact that object
equality *does not* imply object identity. If you happen to notice some
operations producing the same object at one point in time, but the
documentation doesn't promise it, then treat that as an unpredictable
implementation detail and don't rely on it in your code.

-- 
 \       “The best in us does not require the worst in us: Our love of |
  `\     other human beings does not need to be nurtured by delusion.” |
_o__)                             —Sam Harris, at _Beyond Belief 2006_ |
Ben Finney



More information about the Tutor mailing list