[Tutor] lists, name semantics

Alan Gauld alan.gauld at btinternet.com
Sat Apr 18 08:43:03 CEST 2015


On 18/04/15 04:16, Bill Allen wrote:
> 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?

Others have already given some good explanations.
I'll add a slightly different take.

Your confusion starts with your first statement:

 > I have a list defined as my_list = ['a','b','c']

What you should be saying is

I have a list defined as ['a', 'b', 'c']

Thats the list object that you are working with. The object is 
completely separate from the name that you choose to associate
with it.

You then bound that list to a name: my_list.
You could bind it to any number of names but
there would still only be one object:

foo = my_list
bar = foo
baz = my_list

Now I have 4 names all referring to the same list object.

The next source of confusion comes from another mist-statement:

 > differnce between refering to it as my_list or my_list[:]

The [:] at the end is an operator that returns a copy of the list.
So when you use it you are NOT referring to the original list
at all. You are creating a new copy.

So if we now take one of our previous names, say foo, and do:

foo = my_list[:]

foo no longer refers to your original list ['a','b','c']
but to a completely new copy of that list.

If you modify my_list the changes will show up when you look
at bar and baz as well. But foo will be unchanged

my_list[0] = 'z'
print baz   -> prints ['z','b','c'] - the same list as my_list
print foo   -> prints ['a','b','c'] - a different list object

Understanding the separation of names from objects in Python is 
essential to understanding how it works. It is different to many
other languages in this respect.

And understanding the difference between identity and value is also 
important. Two completely different objects can have the same value
and so appear the same but they are in fact entirely different.
Think about two drivers who both buy the exact same model of car.
They may look identical, but they are two separate cars.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list