slice()

The built-in slice() function creates a slice object representing a set of indices specified by range(start, stop, step). This object can be used to extract portions of sequences like strings, lists, or tuples:

Python
>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> even_numbers = numbers[slice(1, None, 2)]
>>> even_numbers
[2, 4, 6, 8]

slice() Signatures

Python Syntax
slice(stop)
slice(start, stop, step=None)

Arguments

Argument Description Default Value
start The initial index of the slice. None (start of the sequence)
stop The ending index of the slice, exclusive. Required argument
step The step between each index in the slice. None (step of 1)

Return Value

  • Returns a slice object that can be used to extract a portion of a sequence.

slice() Examples

With only a stop value:

Python
>>> letters = ["A", "B", "C", "D", "E"]
>>> letters[slice(3)]
['A', 'B', 'C']

With start, stop, and step values:

Python
>>> numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numbers[slice(1, 8, 2)]
[1, 3, 5, 7]

slice() Common Use Cases

The most common use cases for the slice() function include:

  • Extracting a subset of elements from a sequence.
  • Creating copies of sequences.

slice() Real-World Example

Say that you have a list of daily temperatures and you want to extract the temperatures for first day of each week only, skipping weekends:

Python
>>> temperatures = [20, 21, 19, 22, 18, 17, 23, 24, 25, 26, 22, 21, 19, 20]
>>> weekdays = temperatures[slice(0, None, 7)]
>>> weekdays
[20, 24]

In this example, slice(0, None, 7) allows us to select every 7th temperature starting from the first element, effectively picking temperatures for the first day of each week.

Tutorial

Python's Built-in Functions: A Complete Exploration

In this tutorial, you'll learn the basics of working with Python's numerous built-in functions. You'll explore how to use these predefined functions to perform common tasks and operations, such as mathematical calculations, data type conversions, and string manipulations.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 22, 2024 • Reviewed by Dan Bader