Lists: why is this behavior different for index and slice assignments?
Steve Holden
steve at holdenweb.com
Mon Apr 21 22:10:22 EDT 2008
John Salerno wrote:
> 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?
>
Assignment to a list *element* rebinds the single element to the
assigned value. Assignment to a list *slice* has to be of a list, and it
replaces the elements in the slice by assigned elements.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list