[Tutor] how to make a reference to part of list?

Kent Johnson kent37 at tds.net
Mon Oct 2 13:57:31 CEST 2006

Xie Chao wrote:
>       Namely, if  list1 = {1, 2, 3}, and I wanna make a reference, say 
> "ref",  to list1's sublist (which is also of type list), say {2, 3}, so 
> that when I make change to ref[0], then list1[1] will be changed!
>       But how can I make such a reference, 3x!  

There is nothing built-in to Python that will let you do this. I don't 
think it would be too hard to write a class that does what you want for 
basic indexing operations. I would start with a copy of UserList (in 
module UserList). If you go beyond simple indexing and slicing I think 
you will have trouble. Say you have a class RefList that does what you 
want, and suppose you have
a = [1, 2, 3]
b = RefList(a, 1, 2)
b is [2, 3]
c = RefList(a, 0, 1)
c is [1, 2]

Now what is the result of d=b+c? Is it a RefList with two references to 
a, that looks like [1, 2, 2, 3]? What is the value of d after d[1] = 0? 
Is it [1, 0, 0, 3]?

Can you say more about why you want to do this? Maybe there is another 

By the way list literals in Python are written with square brackets [] 
not curly braces {}.


More information about the Tutor mailing list