Home » Programming » Python » Python Slice

How to Use the Python slice() Function, With Examples

The Python slice() function can be used to get a portion of a list, tuple, string, or other sequence. This article will show you how to use it.

Python slice() Function Syntax

Here’s the syntax for the Python slice() function:

slice(START, STOP, STEP)

Note that:

  • slice() does not return the specified portion of an object
    • It returns a slice object which is used to retrieve the specified portion from a sequence – it does not contain the sequence itself.
    • This is probably best demonstrated in the below examples
  • START is the starting position (index) of the sequence you wish to retrieve
    • Optional
    • Defaults to 0
    • It should be an integer
    • START is inclusive – the value at START will be included in the slice
  • STOP is the end position of the portion you wish to retrieve
    • It should be an integer STOP is NOT inclusive – the value at STOP will NOT be included in the slice
  • STEP defines the incrementation of the slicing
    • Optional
    • Defaults to 1
    • It should be an integer
  • START and STOP are indexes, so they start counting at 0!
    • Therefore, the first position is index 0, the second is index 1, and so on.
  • Only STOP needs to be specified when calling slice()
    • If only STOP is specified, START and STEP will take their default values

Slice Objects

The slice() function returns a slice object which contains the information on which portion of the sequence you wish to retrieve. The slice object contains the startstop and step values provided by the slice() function.

The slice object can then be used to retrieve the specified portion of a given sequence.

Examples: Using slice() To Get Part of a Sequence

Here’s how to use slice() to retrieve a subset of a sequence from various data types in Python:

Tuple

What is a tuple? Check out our article here!

Here’s how to slice a tuple:

fruitAndVeg = ("apple", "banana", "grapefruit", "carrot", "eggplant", "potato", "lemon")
vegSlice = slice(3, 6)
veg = fruitAndVeg[vegSlice]
print(veg) # ('carrot', 'eggplant', 'potato')

Above, vegSlice is defined using the slice() method – it contains the information on the start and end position of the slice we wish to read from fruitAndVeg.

The veg variable is then defined by taking that vegSlice from the fruitAndVeg tuple.

Finally, the result is printed, confirming that only the vegetables (the slice from indexes 3 to 5) have been assigned to the veg variable.

Note that the value from index 6 is NOT included in the result – the value at the STOP position is not included!.

List

The slice() function works exactly the same way for lists as it does for tuples above:

colours = ["red", "green", "blue", "yellow", "pink", "purple", "orange"]
first3Slice = slice(3)
first3 = colours[first3Slice]
print(first3) # ['red', 'green', 'blue']

Above, only a single parameter is passed to slice() – it is assumed to be the STOP parameter as START and STEP have default values.

So, the above is treated as slice(0, 3) – and returns the first three items in the list.

String/Text

slice() can be used the same way with string variables, returning a portion of the string:

text = 'LinuxScrew'
screwSlice = slice(5, 10)
print(text[screwSlice]) # 'Screw'

Using Steps

By specifying a step, you’re telling slice() to skip over items in the sequence. Below, a step of 2 is defined – so the result only contains the values at even positions from the sequence:

text = 'LinuxScrew'
screwSlice = slice(0, 5, 2)
print(text[screwSlice]) # 'Lnx'

Using Negative Indexes

Negative indexes can be passed to slice() to work backward through the sequence:

text = 'LinuxScrew'
screwSlice = slice(-10, -5)
print(text[screwSlice]) # 'Linux'

Note that the sequence is still read front to back, but the position is calculated from back to front when working out which part of the sequence to retrieve.

Negative Steps

Negative steps can be used to read backwards through the sequence.

Below, the resulting slice of text is reversed due to the use of a negative step – the sequence is read back to front:

text = 'LinuxScrew'
screwSlice = slice(10, 4, -1)
print(text[screwSlice]) # 'wercS' (it's 'Screw' backwards)

 

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment