adding a character to the last string element of a list

  • Thread starter Philippe C. Martin
  • Start date
P

Philippe C. Martin

Hi,

I have the following question:

l = ['ABCDE','FGHI']
l[1:] #returns ['FGHI']
l[1:][0] #return 'FGHI'

a = l[1:][0] + 'J' #a becomes 'FGHIJ'

l[1:][0] += 'J' #NO ERROR BUT l[1:][0] == 'FGHI'


What am I missing ?

Thanks,

Philippe
 
P

Peter Hansen

Philippe said:
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
 
P

Philippe C. Martin

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

Regards,

Philippe



Peter said:
Philippe said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top