Lists: why is this behavior different for index and sliceassignments?
tjreedy at udel.edu
Thu Apr 24 10:56:26 CEST 2008
"John Salerno" <johnjsal at gmailNOSPAM.com> wrote in message
news:480ffaae$0$11639$607ed4bc at cv.net...
| John Machin wrote:
| > Deletion occurs *only* in the corner case where there are no "assigned
| > elements" i.e. only if the RHS list (sequence) is *empty*.
| Oh, it was my understanding that deletion always occurs, even when the
| section is being assigned a non-empty value, i.e. delete the slice and
| insert new value.
Slice replacement means replace the slice with a new slice generated from
the iterable on the left. John meant that deletion only only happens when
the replacement is empty. Yes, deletion always occurs, but usually
addition also occurs, so the net result is replacement rather than just
| > there would be no point at all in the language having assignment to a
| > slice -- del L[0:2] would suffice.
| Right, but I'm wondering why a statement like
| L[0:2] = 
| doesn't assign an empty list as the new element in L. For example:
Because, as others already told you, slice replacement is slice
replacement, not item assignment. When you say to replace the slice with
nothing, the deleted slice is replaced with nothing.
L[0:2] = []
says to replace the slice with a slice consisting of one item -- 
That will get you what you are expecting.
| L = [1, 2, 3, 4, 5]
| L[0:2] = 
| Why doesn't L now equal [, 3, 4, 5] as it does with an index
| > >>> L[0:2] = tuple('foobar')
L[0:2] = 'foobar' has same effect because s string is an iterable.
| > >>> L
| > ['f', 'o', 'o', 'b', 'a', 'r', 3, 4, 5]
| Hmm...why doesn't L equal [('f', 'o', 'o', 'b', 'a', 'r'), 3, 4, 5] ?
| Shouldn't L be a 4 item list instead of 9?
Because you replaced 2 items with 6.
L[0:2] = ['foobar'] will replace 2 with 1, leaving 4
More information about the Python-list