Lists: why is this behavior different for index and slice assignments?

John Salerno johnjsal at gmailNOSPAM.com
Wed Apr 23 23:12:33 EDT 2008


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.

Otherwise
> 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:

L = [1, 2, 3, 4, 5]
L[0:2] = []

Why doesn't L now equal [[], 3, 4, 5] as it does with an index assignment?

>  >>> L[0:2] = tuple('foobar')
>  >>> 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?



More information about the Python-list mailing list