[Tutor] lists, name semantics

Dave Angel davea at davea.name
Sat Apr 18 07:03:34 CEST 2015


On 04/17/2015 11:51 PM, Ben Finney wrote:
> 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.
>

Great description, if the OP really wants that level of detail.  But I 
think what he needs to know first is:

If you change foo, like       (untested)
     foo[1] = "new"

then you'll see that bar also changes (since it's just another name for 
the exact same object).
 >>> bar
['a', 'new', 'c']

But baz does not, since it's bound to a copy of the object.
 >>> baz
['a', 'b', 'c'\
-- 
DaveA


More information about the Tutor mailing list