Reputation: 479
Why is a[len(a):] = [x]
equivalent to a.append(x)
, but a[len(a)] = [x]
gives an out of range error?
Upvotes: 3
Views: 462
Reputation: 122116
Per the documentation (emphasis mine):
If the target is a subscription: ...
If the primary is a mutable sequence object (such as a list), the subscript must yield a plain integer. If it is negative, the sequence’s length is added to it. The resulting value must be a nonnegative integer less than the sequence’s length, and the sequence is asked to assign the assigned object to its item with that index. If the index is out of range, IndexError is raised (assignment to a subscripted sequence cannot add new items to a list)
...
If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to (small) integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the object allows it.
So assignment to a slice can change the length of the list, but assignment to an index (subscription) cannot.
Upvotes: 4
Reputation: 310097
Python's slicing is generally more "forgiving" than indexing with a number (by design). For example:
lst = []
lst[1:100] # No exception here.
I think that the slice assignment case is just an extension of this "forgivingness". Interestingly enough, you can even use indices that are wildly out of range:
a = []
a[100:101] = ['foo']
Upvotes: 2
Reputation: 1124070
Because that's an explicit choice the language made; assigning to indices requires those indices to exist. Assigning to slices will expand or contract the list as needed to accommodate a new size.
Upvotes: 3