[Tutor] lists, name semantics

Martin A. Brown martin at linux-ip.net
Sat Apr 18 05:42:11 CEST 2015


Good evening Bill,

> 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[:]? 
> These seem equivalent to me.  Is that the case?  Is there any 
> nuance I am missing here?  Situations where one form should be 
> used as opposed to the other?

Yes, there is a difference.  It can (conceivably) by subtle, but it 
is simple.

Let's start with the following.  I will call the list by the 
variable name l.  So, Python ('the computer') has stored the list in 
memory.  After executing this command, if I want to retrieve that 
data, I can call it by the variable named 'l':

   l = ['a', 'b', 'c']

Now consider the following two statements.

   case A:    k = l
   case B:    m = l[:]

These perform two different operations.  The first simply says "Hey, 
when I refer to variable k, I want it to behave exactly like I had 
used the variable named l."  The second says "Please give me a COPY 
of everything contained in the variable named l and let me refer to 
that as the variable named m."

What is the nuance of difference?  Where are the data stored in 
memory?  Let's take case A:

   >>> l = ['a', 'b', 'c']
   >>> k = l
   >>> k == l
   True
   >>> k is l
   True

So, you see, not only are k and l refer to the same list contents, 
but they point to the same place in computer memory where the list 
is stored.  The variables named l and k are just different names for 
the same thing (data).

Now, let's see what happens when we use case B, copying the list 
(strictly speaking you are slicing the entire list, see Python 
documentation).

   >>> m = l[:]
   >>> m == l
   True
   >>> m is l
   False

What's different here?  Well, the variables m and l have the same 
contents, and are therefore equal (this will compare all elements of 
the list for equality).  But, m and l are not the same thing (data)! 
Though they contain the same data, the list contents are stored in 
different places in computer memory.

This subtlety means that you probably do not want to say my_list[:] 
unless you really want to use up all the memory to store the same 
data twice.  You may wish to do that, but given your question about 
nuance, I would point out that this is no nuance but a significant 
feature which can surprise you later if you do not understand what 
is happening with the slicing notation.

Best of luck and enjoy a fried slice of Python!

-Martin

  [0] https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list