search
Search
Login
Math ML Join our weekly DS/ML newsletter
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
A
A
brightness_medium
share
arrow_backShare
Twitter
Facebook

Python | slice constructor

Built-in Functions
chevron_right
Documentation
schedule Jul 1, 2022
Last updated
local_offer Python
Tags

Python's slice(~) constructor returns a slice object that usually contains a portion of a sequence.

Parameters

1. start | integer | optional

The start position for the slice object (inclusive). Defaults to 0.

2. stop | integer

The stop position for the slice object (non-inclusive).

3. step | integer | optional

Increment for each integer in the sequence. Defaults to 1.

NOTE

Although we can use slice(start, stop, step) notation, the most common notation is indexing syntax sequence[start:stop:step].

Return value

A slice object that usually contains a portion of a sequence.

Examples

Basic usage

To create a slice object from start position 0 to stop position 5:

numbers = [0, 1, 2, 3, 4, 5]
slice_object = slice(5)
s1 = numbers[slice_object]
s2 = numbers[:5]
print(s1)
print(s2)
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]

We can see that both notation forms yield the same result.

Start parameter

To specify the start of the slice:

numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:5])
[1, 2, 3, 4]

We can see that the resulting slice begins at value of index position 1 of numbers.

Step parameter

To specify the step of the slice:

numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:6:2])
[1, 3, 5]

From start value of 1, we increment by 2 until we reach the stop value of 6.

Negative Index

To specify negative start, stop and step:

letters = ('S', 'k', 'y', 'T', 'o', 'w', 'n', 'e', 'r')
print(letters[-1:-5:-1])
('r', 'e', 'n', 'w')

By specifying start of -1 we start at the last element of the tuple, ad a step of -1 means we work backwards by one index position increment at a time until index position -5 (fifth to last element in original tuple).

mail
Join our newsletter for updates on new DS/ML comprehensive guides (spam-free)
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!