slice

Full name
slice
Library
Built-in
Syntax

class slice(stop)

class slice(start, stop [, step])

Description

The slice class returns an object representing the indices specified by range(start, stop, step).

Parameters
  • start: First index to generate in the sequence.
  • stop: Limit value of the index to be generated.
  • step: (Optional) value to add to each index to generate the next one.
Result

The result is an object of class slice.

Examples

We can create a slice object that includes references to indexes 1, 3 and 5 (that is, indexes starting at 2, ending at 6 and with a jump of 2) with the following code:

index = slice(1, 6, 2)
index

slice(1, 6, 2)

Now if we have, for example, a list:

a = list("ABCDEFGH")
a

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

...we can extract the elements referenced by our indexes in the following way:

a[index]

['B', 'D', 'F']

Submitted by admin on Tue, 01/19/2021 - 09:49