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

John Machin sjmachin at lexicon.net
Tue Apr 22 20:30:46 EDT 2008


John Salerno wrote:
> Steve Holden wrote:
> 
>> Assignment to a list *element* rebinds the single element to the 
>> assigned value. 
> 
> Ok, I understand that.
> 
> Assignment to a list *slice* has to be of a list [or iterable, as per 
> Duncan], and it
>> replaces the elements in the slice by assigned elements.
> 
> 
> I don't understand the second part of that sentence. I'm assuming "it" 
> refers to the list being assigned, "replaces the elements" is 
> self-evident, but what does "by assigned elements" refer to? It seems 
> when you assign a list to a list slice, nothing gets replaced, the slice 
> just gets deleted.

Deletion occurs *only* in the corner case where there are no "assigned 
elements" i.e. only if the RHS list (sequence) is *empty*. Otherwise 
there would be no point at all in the language having assignment to a 
slice -- del L[0:2] would suffice.

Study these:

 >>> L = [1, 2, 3, 4, 5]
 >>> L[0:2] = []
 >>> L
[3, 4, 5]
 >>> L = [1, 2, 3, 4, 5]
 >>> L[0:2] = ['whatever']
 >>> L
['whatever', 3, 4, 5]
 >>> L = [1, 2, 3, 4, 5]
 >>> L[0:2] = tuple('foobar')
 >>> L
['f', 'o', 'o', 'b', 'a', 'r', 3, 4, 5]
 >>>



More information about the Python-list mailing list