@@ -370,7 +370,90 @@ \section{Extended Slices\label{section-slices}}
370370'dcba'
371371\end {verbatim }
372372
373+ as well as tuples and arrays.
373374
375+ If you have a mutable sequence (i.e. a list or an array) you can
376+ assign to or delete an extended slice, but there are some differences
377+ in assignment to extended and regular slices. Assignment to a regular
378+ slice can be used to change the length of the sequence:
379+
380+ \begin {verbatim }
381+ >>> a = range(3)
382+ >>> a
383+ [0, 1, 2]
384+ >>> a[1:3] = [4, 5, 6]
385+ >>> a
386+ [0, 4, 5, 6]
387+ \end {verbatim }
388+
389+ but when assigning to an extended slice the list on the right hand
390+ side of the statement must contain the same number of items as the
391+ slice it is replacing:
392+
393+ \begin {verbatim }
394+ >>> a = range(4)
395+ >>> a
396+ [0, 1, 2, 3]
397+ >>> a[::2]
398+ [0, 2]
399+ >>> a[::2] = range(0, -2, -1)
400+ >>> a
401+ [0, 1, -1, 3]
402+ >>> a[::2] = range(3)
403+ Traceback (most recent call last):
404+ File "<stdin>", line 1, in ?
405+ ValueError: attempt to assign list of size 3 to extended slice of size 2
406+ \end {verbatim }
407+
408+ Deletion is more straightforward:
409+
410+ \begin {verbatim }
411+ >>> a = range(4)
412+ >>> a[::2]
413+ [0, 2]
414+ >>> del a[::2]
415+ >>> a
416+ [1, 3]
417+ \end {verbatim }
418+
419+ One can also now pass slice objects to builtin sequences
420+ \method {__getitem__} methods:
421+
422+ \begin {verbatim }
423+ >>> range(10).__getitem__(slice(0, 5, 2))
424+ [0, 2, 4]
425+ \end {verbatim }
426+
427+ or use them directly in subscripts:
428+
429+ \begin {verbatim }
430+ >>> range(10)[slice(0, 5, 2)]
431+ [0, 2, 4]
432+ \end {verbatim }
433+
434+ To make implementing sequences that support extended slicing in Python
435+ easier, slice ojects now have a method \method {indices} which given
436+ the length of a sequence returns \code {(start, stop, step)} handling
437+ omitted and out-of-bounds indices in a manner consistent with regular
438+ slices (and this innocuous phrase hides a welter of confusing
439+ details!). The method is intended to be used like this:
440+
441+ \begin {verbatim }
442+ class FakeSeq:
443+ ...
444+ def calc_item(self, i):
445+ ...
446+ def __getitem__(self, item):
447+ if isinstance(item, slice):
448+ return FakeSeq([self.calc_item(i)
449+ in range(*item.indices(len(self)))])
450+ else:
451+ return self.calc_item(i)
452+ \end {verbatim }
453+
454+ From this example you can also see that the builtin `` \var {slice}''
455+ object is now the type of slice objects, not a function (so is now
456+ consistent with \var {int}, \var {str}, etc from 2.2).
374457
375458% ======================================================================
376459\section {Other Language Changes }
0 commit comments