Detailed Explanation of slice Case of python Built in Function

  • 2021-11-29 08:06:00
  • OfStack

English document:

class slice(stop)class slice(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]. See itertools.islice() for an alternate version that returns an iterator.

Description:

1. The function is actually the constructor of a slice class and returns a slice object.

2. The slice object consists of three attributes, start, stop, and step. The default values of start and step are None. Slicing object is mainly used to slicing sequence objects to get corresponding elements.


>>> help(slice)
class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])
 |  
 |  Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).
 |  
 |  Methods defined here:
 |  
 |  ...# Omission #
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  start
 |  
 |  step
 |  
 |  stop
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> a[None:5:None] # start step Explicitly None
[0, 1, 2, 3, 4]
>>> a[:5:] # start step Default to None
[0, 1, 2, 3, 4]
>>> a[2:5:None] # step Explicitly None
[2, 3, 4]
>>> a[2:5:] # step Default to None
[2, 3, 4]
>>> a[1:10:3]
[1, 4, 7]

3. The functions corresponding to the three attributes start, stop, step and slice of the slice object also have three corresponding parameters start, stop and step, and their values will be paid to start, stop and step of the slice object respectively.


>>> c1 = slice(5) #  Definition c1
>>> c1
slice(None, 5, None)
>>> c2 = slice(2,5) #  Definition c2
>>> c2
slice(2, 5, None)
>>> c3 = slice(1,10,3) #  Definition c3
>>> c3
slice(1, 10, 3)
>>> a[c1] #  And a[:5:] The results are the same 
[0, 1, 2, 3, 4]
>>> a[c2] #  And a[2:5:] The results are the same 
[2, 3, 4]
>>> a[c3] #  And a[1:10:3] The results are the same 
[1, 4, 7]

Related articles: