Slice of py
- VC Healy
- May 27, 2020
- 4 min read
classslice(stop)classslice(start,stop[,step])
Return a slice object representing the set of indices specified by range(start, stop, step).
The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default).
They have no other explicit functionality; however they are used by Numerical Python and other third party extensions.
Slice objects are also generated when extended indexing syntax is used.
For example:
a[start:stop:step] or a[start:stop, i].
start
Optional. An integer number specifying at which position to start the slicing. Default is 0
stop
An integer number specifying at which position to end the slicing (Not inclusive)
step
Optional. An integer number specifying the step of the slicing. Default is 1
Negative Indexing
When slicing in reverse it is better to use the negative indice values of the items in the element being sliced.
Where positive values are being used for a reversed slice, with indice[0] required to be part of the slice.. Then do not use -1, as the stop value. Instead leave the value None.
-1 would be assumed by python to be part of a negative indice[-1] the item of the element last on the right. This would then give an empty slice.
(3:-1:-1) would wrongly be seen as start at 3, stop at -1 with -1 step(going right to left)
This would start indice [3], try to go right to left to go to -1. As indice[-1] is to the right of 3 an error would be raised.
Slicings
A slicing selects a range of items in a sequence object (e.g., a string, tuple or list).
Slicings may be used as expressions or as targets in assignment or del statements.
The syntax for a slicing:
slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= expression | proper_slice
proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]
lower_bound ::= expression
upper_bound ::= expression
stride ::= expression
There is ambiguity in the formal syntax here: anything that looks like an expression list also looks like a slice list, so any subscription can be interpreted as a slicing.
Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice).
The semantics for a slicing are as follows.
The primary is indexed (using the same __getitem__() method as normal subscription) with a key that is constructed from the slice list, as follows.
If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key.
The conversion of a slice item that is an expression is that expression.
The conversion of a proper slice is a slice object whose start, stop and step attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting None for missing expressions.
Mutable Sequence Types
The operations in the following table are defined on mutable sequence types.
The collections.abc.MutableSequence ABC is provided to make it easier to correctly implement these operations on custom sequence types.
In the table s is an instance of a mutable sequence type, t is any iterable object and x is an arbitrary object that meets any type and value restrictions imposed by s
(for example, bytearray only accepts integers that meet the value restriction 0 <= x <= 255).
Operation Result Notes
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t (1)
del s[i:j:k] removes the elements of s[i:j:k] from the list
s.append(x) appends x to the end of the sequence (same as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:]) (5)
s.copy() creates a shallow copy of s (same as s[:]) (5)
s.extend(t) or s += t extends s with the contents of t (for the most part the same as s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times (6)
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop([i]) retrieves the item at i and also removes it from s (2)
s.remove(x) remove the first item from s where s[i] is equal to x (3)
s.reverse() reverses the items of s in place (4)
Notes:
t must have the same length as the slice it is replacing.
The optional argument i defaults to -1, so that by default the last item is removed and returned.
remove() raises ValueError when x is not found in s.
The reverse() method modifies the sequence in place for economy of space when reversing a large sequence. To remind users that it operates by side effect, it does not return the reversed sequence.
clear() and copy() are included for consistency with the interfaces of mutable containers that don’t support slicing operations (such as dict and set). copy() is not part of the collections.abc.MutableSequence ABC, but most concrete mutable sequence classes provide it. New in version 3.3: clear() and copy() methods.
The value n is an integer, or an object implementing __index__(). Zero and negative values of n clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for s * n under Common Sequence Operations.
PEP 3132- Extended Iterable Unpacking
The specification for the *target feature.
Comments