adding a character to the last string element of a list

Philippe C. Martin philippe at philippecmartin.com
Tue Jul 5 22:19:09 EDT 2005


Thanks, I though it was a reference (tough to implement I'm sure)

Regards,

Philippe



Peter Hansen wrote:

> Philippe C. Martin wrote:
>> l = ['ABCDE','FGHI']
> 
> Okay so far...
> 
>> l[1:] #returns ['FGHI']
> 
> Which is a _copy_ (via slicing) of part of the list.  Another way of
> saying this is that it is a _new_ list which has a copy of the
> references from the appropriate part of the old list.
> 
> Try "l[1:] is l[1:]" to prove that...
> 
>> l[1:][0] #return 'FGHI'
> 
> Sure does.  From the new list.
> 
>> a = l[1:][0] + 'J' #a becomes 'FGHIJ'
> 
> Because you are actually storing a reference to the new list, whose
> first element you have modified.
> 
>> l[1:][0] += 'J' #NO ERROR BUT l[1:][0] == 'FGHI'
> 
> You are modifying the first element of the *copy* of the slice of the
> list, but you don't ever store a copy of it.  When you try to check what
> happened with the second part, you are creating yet another copy of part
> of the list and sure enough the original has never been changed.
> 
>> What am I missing ?
> 
> That slicing makes copies.  If you directly access the element in the
> first list (without using a slice) it will work.
> 
> (I think I've got most of the correct...)
> 
> -Peter




More information about the Python-list mailing list