adding a character to the last string element of a list
Peter Hansen
peter at engcorp.com
Tue Jul 5 19:56:34 EDT 2005
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