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

John Salerno johnjsal at gmailNOSPAM.com
Tue Apr 22 03:45:53 CEST 2008


Hey all. I've decided I let my Python skills (minor though they were) 
slip away so I started reading the new edition of Learning Python to 
brush up. I just read about lists again and I'm wondering if someone 
could explain what's going on under the hood that makes index and slice 
assignments behave differently when assigning an empty list.

For example:

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

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

So the question is, when you assign an empty list to an index, why does 
it insert an empty list, but when you assign an empty list to a slice, 
it simply deletes the slice?

Thanks!



More information about the Python-list mailing list