Python slice() Function

Example

Create a tuple and a slice object. Use the slice object to get the first two items of the tuple only:

a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(2)
print(a[x])

Run Instance

Definition and Usage

The slice() function returns a slice object (slice).

The slice object is used to specify how to cut a sequence. You can specify where to start cutting and where to end cutting. You can also specify the step, such as cutting every other item.

Syntax

slice(start, end, step)

Parameter Value

Parameter Description
start Optional. Integer, specifies the position to start the cut. The default is 0.
end Optional. Integer, specifies the position to end the cut.
step Optional. Integer, specifies the step value for cutting. The default is 1.

More Examples

Example

Create a tuple and a slice object. Start the slice object at position 3 and cut at position 5, and return the result:

a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(3, 5)
print(a[x])

Run Instance

Example

Create a tuple and a slice object. Use the step parameter to return every third item:

a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(0, 8, 3)
print(a[x])

Run Instance