Assignment to slice
james at logicalprogression.net
Wed Jan 21 18:42:07 CET 2004
On Wednesday 21 January 2004 5:01 pm, Rich Krauter wrote:
> I do not understand why python behaves the way it does
> in the following code:
> Here, Python doesn't like that I'm assigning
> out-of-range. OK. That's fine.
> >>> x = 
> >>> x = 3
> Traceback (most recent call last):
> File "<interactive input>", line 1, in ?
> IndexError: list assignment index out of range
> However, the following seems very strange. Assigning
> to a slice, over non-existent array indexes, sets x
> and x.
> >>> x[2:5] = [3,4]
> >>> x
> >>> x[1000:9000] = 
> >>> x
> [3, 4, 5]
> Why does assigning to a slice of non-existent array
> elements fill in the array, starting with the first
> empty array position? (Acts like .append() or
> Why not raise an out-of-bounds exception here too?
> Wouldn't that be more consistent with the first case,
> in which I tried to assign out-of-range, and got an
> IMO, at least the first index in the slice should be
> required to exist in the array. If not, raise an
> exception. That way, assigning to the slice fills in
> the array in a predicatable way without having to do
> len() checks first to ensure that you know where in
> the array the slice is actually going to be inserted.
> But I'm sure it is the way it is for a good reason.
> Hopefully someone can clue me in.
> Thank you in advance.
This doesn't answer you fully but Python is at least consistent in that
slicing - as opposed the indexing of your first case - *never* raises an
IndexError. It's not unique to assignment. "print x[1000:9000]" works too.
The fact that slices can extend outside the current range is useful.
Otherwise you couldn't use them to extend sequences. Adding to the end
would still be possible with your proposed restriction on first index., but
what if you wanted to add stuff to the *start* of the list. Currently this
>>> x = [1, 2, 3]
>>> x[-10:-9] = 
[54, 1, 2, 3]
In this case to be consistent you must insist that the second index exist in
the array, i.e. insist on:
>>> x[-4:-3] = 
James Henderson, Logical Progression Ltd.
More information about the Python-list