search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
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

Python | slice constructor

schedule Aug 12, 2023
Last updated
local_offer
Python
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

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).

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
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!