You create a slice by calling slice with the same fields you would use if doing [start:end:step] notation:

sl = slice(0,4)

To use the slice, just pass it as if it were the index into a list or string:

>>> s = "ABCDEFGHIJKL"
>>> sl = slice(0,4)
>>> print(s[sl])
'ABCD'

Let's say you have a file of fixed-length text fields. You could define a list of slices to easily extract the values from each "record" in this file.

data = """\
0010GEORGE JETSON    12345 SPACESHIP ST   HOUSTON       TX
0020WILE E COYOTE    312 ACME BLVD        TUCSON        AZ
0030FRED FLINTSTONE  246 GRANITE LANE     BEDROCK       CA
0040JONNY QUEST      31416 SCIENCE AVE    PALO ALTO     CA""".splitlines()


fieldslices = [slice(*fielddef) for fielddef in [
    (0,4), (4, 21), (21,42), (42,56), (56,58),
    ]]
fields = "id name address city state".split()

for rec in data:
    for field,sl in zip(fields, fieldslices):
        print("{} : {}".format(field, rec[sl]))
    print('')

# or this same code using itemgetter, to make a function that
# extracts all slices from a string into a tuple of values
import operator
rec_reader = operator.itemgetter(*fieldslices)
for rec in data:
    for field, field_value in zip(fields, rec_reader(rec)):
        print("{} : {}".format(field, field_value))
    print('')

Prints:

id : 0010
name : GEORGE JETSON    
address : 12345 SPACESHIP ST   
city : HOUSTON       
state : TX

id : 0020
name : WILE E COYOTE    
address : 312 ACME BLVD        
city : TUCSON        
state : AZ

id : 0030
name : FRED FLINTSTONE  
address : 246 GRANITE LANE     
city : BEDROCK       
state : CA

id : 0040
name : JONNY QUEST      
address : 31416 SCIENCE AVE    
city : PALO ALTO     
state : CA
Answer from PaulMcG on Stack Overflow
🌐
Python
docs.python.org › 3 › c-api › slice.html
Slice Objects — Python 3.14.7 documentation
Return the length of the slice. Always successful. Doesn’t call Python code. Added in version 3.6.1. ... Part of the Stable ABI. The type of Python Ellipsis object.
Top answer
1 of 6
113

You create a slice by calling slice with the same fields you would use if doing [start:end:step] notation:

sl = slice(0,4)

To use the slice, just pass it as if it were the index into a list or string:

>>> s = "ABCDEFGHIJKL"
>>> sl = slice(0,4)
>>> print(s[sl])
'ABCD'

Let's say you have a file of fixed-length text fields. You could define a list of slices to easily extract the values from each "record" in this file.

data = """\
0010GEORGE JETSON    12345 SPACESHIP ST   HOUSTON       TX
0020WILE E COYOTE    312 ACME BLVD        TUCSON        AZ
0030FRED FLINTSTONE  246 GRANITE LANE     BEDROCK       CA
0040JONNY QUEST      31416 SCIENCE AVE    PALO ALTO     CA""".splitlines()


fieldslices = [slice(*fielddef) for fielddef in [
    (0,4), (4, 21), (21,42), (42,56), (56,58),
    ]]
fields = "id name address city state".split()

for rec in data:
    for field,sl in zip(fields, fieldslices):
        print("{} : {}".format(field, rec[sl]))
    print('')

# or this same code using itemgetter, to make a function that
# extracts all slices from a string into a tuple of values
import operator
rec_reader = operator.itemgetter(*fieldslices)
for rec in data:
    for field, field_value in zip(fields, rec_reader(rec)):
        print("{} : {}".format(field, field_value))
    print('')

Prints:

id : 0010
name : GEORGE JETSON    
address : 12345 SPACESHIP ST   
city : HOUSTON       
state : TX

id : 0020
name : WILE E COYOTE    
address : 312 ACME BLVD        
city : TUCSON        
state : AZ

id : 0030
name : FRED FLINTSTONE  
address : 246 GRANITE LANE     
city : BEDROCK       
state : CA

id : 0040
name : JONNY QUEST      
address : 31416 SCIENCE AVE    
city : PALO ALTO     
state : CA
2 of 6
41

Square brackets following a sequence denote either indexing or slicing depending on what's inside the brackets:

>>> "Python rocks"[1]    # index
'y'
>>> "Python rocks"[1:10:2]    # slice
'yhnrc'

Both of these cases are handled by the __getitem__() method of the sequence (or __setitem__() if on the left of an equals sign.) The index or slice is passed to the methods as a single argument, and the way Python does this is by converting the slice notation, (1:10:2, in this case) to a slice object: slice(1,10,2).

So if you are defining your own sequence-like class or overriding the __getitem__ or __setitem__ or __delitem__ methods of another class, you need to test the index argument to determine if it is an int or a slice, and process accordingly:

def __getitem__(self, index):
    if isinstance(index, int):
        ...    # process index as an integer
    elif isinstance(index, slice):
        start, stop, step = index.indices(len(self))    # index is a slice
        ...    # process slice
    else:
        raise TypeError("index must be int or slice")

A slice object has three attributes: start, stop and step, and one method: indices, which takes a single argument, the length of the object, and returns a 3-tuple: (start, stop, step).

🌐
W3Schools
w3schools.com › python › ref_func_slice.asp
Python slice() Function
A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g.
🌐
The Python Coding Stack
thepythoncodingstack.com › the python coding stack › a slicing story
A Slicing Story - by Stephen Gruppetta
June 25, 2024 - You can read more about __getitem__() in The Manor House, the Oak-Panelled Library, the Vending Machine, and Python's `__getitem__()`. In this new class called TestList, which inherits from list, you first print the value and data type of the argument in the __getitem__() method, and then you call the list's __getitem__() method and return its value. This is what super().__getitem__(item) does since list is the superclass for TestList. The syntax 2:7 within the square brackets represents a slice object.
🌐
Read the Docs
python.readthedocs.io › fr › stable › c-api › slice.html
Slice Objects — documentation Python 3.6.1
Usable replacement for PySlice_GetIndices(). Retrieve the start, stop, and step indices from the slice object slice assuming a sequence of length length, and store the length of the slice in slicelength. Out of bounds indices are clipped in a manner consistent with the handling of normal slices. Returns 0 on success and -1 on error with exception set. Modifié dans la version 3.2: The parameter type for the slice parameter was PySliceObject* before. ... © Copyright 2001-2017, Python Software Foundation.
🌐
Towards Data Science
towardsdatascience.com › home › latest › slicing in python: a comprehensive guide
Slicing in Python: A Comprehensive Guide | Towards Data Science
January 16, 2025 - It enables you to keep the information on how to slice a data sequence - something you cannot do using a range. You create slice objects using the built-in slice class, which takes start, stop, and step parameters.
Find elsewhere
🌐
Lbl
davis.lbl.gov › Manuals › PYTHON-2.3.3 › api › slice-objects.html
7.5.7 Slice Objects
December 19, 2003 - Return value: New reference. Return a new slice object with the given values. The start, stop, and step parameters are used as the values of the slice object attributes of the same names. Any of the values may be NULL, in which case the None will be used for the corresponding attribute.
🌐
Python Morsels
pythonmorsels.com › implementing-slicing
Implementing slicing - Python Morsels
March 27, 2023 - That way slicing ProxySequence objects will always return a ProxySequence, just as slicing a list always returns a list and slicing a string always returns a string. >>> string = "abcdefghi" >>> p = ProxySequence(string) >>> p[1:] ProxySequence('bcdefghi') Python's slicing syntax is powered by slice objects.
🌐
Real Python
realpython.com › ref › builtin-functions › slice
slice() | Python’s Built-in Functions – Real Python
The built-in slice() function creates a slice object representing a set of indices specified by range(start, stop, step).
🌐
Codecademy
codecademy.com › docs › python › built-in functions › slice()
Python | Built-in Functions | slice() | Codecademy
September 26, 2025 - The slice() function creates a slice object that specifies how to slice sequences like strings, lists, tuples, and ranges. It provides a way to extract specific portions of sequences by defining the start, stop, and step parameters, offering ...
🌐
Data Science Discovery
discovery.cs.illinois.edu › guides › DataFrame-Row-Selection › dataframe-slice-objects
Slice Objects and DataFrames - Data Science Discovery
August 11, 2022 - Reset Code Run All to Here Python Output: ``` One way to generate a slice object is with the slice function. There are three possible parameters: start, stop, and step. They follow the format: slice(start = 0, stop, step = 1) If not specified, ...
🌐
DEV Community
dev.to › mike-vincent › quarks-outlines-python-slice-objects-2dea
Quark's Outlines: Python Slice Objects - DEV Community
May 9, 2026 - You can also create a slice object yourself using the built-in slice() function. A slice object has three parts: a start, a stop, and a step. These tell Python where to begin, where to end, and how far to jump between values.
🌐
Reddit
reddit.com › r/python › i never realized how complicated slice assignments are in python...
r/Python on Reddit: I never realized how complicated slice assignments are in Python...
October 4, 2024 -

I’ve recently been working on a custom mutable sequence type as part of a personal project, and trying to write a __setitem__ implementation for it that handles slices the same way that the builtin list type does has been far more complicated than I realized, and left me scratching my head in confusion in a couple of cases.

Some parts of slice assignment are obvious or simple. For example, pretty much everyone knows about these cases:

>>> l = [1, 2, 3, 4, 5]
>>> l[0:3] = [3, 2, 1]
>>> l
[3, 2, 1, 4, 5]

>>> l[3:0:-1] = [3, 2, 1]
>>> l
[1, 2, 3, 4, 5]

That’s easy to implement, even if it’s just iterative assignment calls pointing at the right indices. And the same of course works with negative indices too. But then you get stuff like this:

>>> l = [1, 2, 3, 4, 5]
>>> l[3:6] = [3, 2, 1]
>>> l
[1, 2, 3, 3, 2, 1]

>>> l = [1, 2, 3, 4, 5]
>>> l[-7:-4] = [3, 2, 1]
>>> l
[3, 2, 1, 2, 3, 4, 5]

>>> l = [1, 2, 3, 4, 5]
>>> l[12:16] = [3, 2, 1]
>>> l
[1, 2, 3, 4, 5, 3, 2, 1]

Overrunning the list indices extends the list in the appropriate direction. OK, that kind of makes sense, though that last case had me a bit confused until I realized that it was likely implemented originally as a safety net. And all of this is still not too hard to implement, you just do the in-place assignments, then use append() for anything past the end of the list and insert(0) for anything at the beginning, you just need to make sure you get the ordering right.

But then there’s this:

>>> l = [1, 2, 3, 4, 5]
>>> l[6:3:-1] = [3, 2, 1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 3 to extended slice of size 1

What? Shouldn’t that just produce [1, 2, 3, 4, 1, 2, 3]? Somehow the moment there’s a non-default step involved, we have to care about list boundaries? This kind of makes sense from a consistency perspective because using a step size other than 1 or -1 could end up with an undefined state for the list, but it was still surprising the first time I ran into it given that the default step size makes these kind of assignments work.

Oh, and you also get interesting behavior if the length of the slice and the length of the iterable being assigned don’t match:

>>> l = [1, 2, 3, 4, 5]
>>> l[0:2] = [3, 2, 1]
>>> l
[3, 2, 1, 3, 4, 5]

>>> l = [1, 2, 3, 4, 5]
>>> l[0:4] = [3, 2, 1]
>>> l
[3, 2, 1, 5]

If the iterable is longer, the extra values get inserted after last index in the slice. If the slice is longer, the extra indices within the list that are covered by the slice but not the iterable get deleted. I can kind of understand this logic to some extent, though I have to wonder how many bugs there are out in the wild because of people not knowing about this behavior (and, for that matter, how much code is actually intentionally using this, I can think of a few cases where it’s useful, but for all of them I would preferentially be using a generator or filtering the list instead of mutating it in-place with a slice assignment)

Oh, but those cases also throw value errors if a step value other than 1 is involved...

>>> l = [1, 2, 3, 4, 5]
>>> l[0:4:2] = [3, 2, 1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 3 to extended slice of size 2

TLDR for anybody who ended up here because they need to implement this craziness for their own mutable sequence type:

  1. Indices covered by a slice that are inside the sequence get updated in place.

  2. Indices beyond the ends of the list result in the list being extended in those directions. This applies even if all indices are beyond the ends of the list, or if negative indices are involved that evaluate to indices before the start of the list.

  3. If the slice is longer than the iterable being assigned, any extra indices covered by the slice are deleted (equivalent to del l[i]).

  4. If the iterable being assigned is longer than the slice, any extra items get inserted into the list after the end of the slice.

  5. If the step value is anything other than 1, cases 2, 3, and 4 instead raise a ValueError complaining about the size mismatch.

🌐
Python
docs.python.org › 3 › builtins › functions.html
Built-in Functions — Python 3.14.7 documentation
name need not be a Python identifier as defined in Names (identifiers and keywords) unless the object chooses to enforce that, for example in a custom __getattribute__() or via __slots__. An attribute whose name is not an identifier will not be accessible using the dot notation, but is accessible through getattr() etc.. ... Since private name mangling happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to set it with setattr(). ... Return a slice object representing the set of indices specified by range(start, stop, step).
🌐
Linode
linode.com › docs › guides › how-to-slice-and-index-strings-in-python
How to Slice and Index Strings in Python | Linode Docs
January 28, 2022 - A predefined slice object helps avoid coding errors and assists with modularity and maintainability. To create a substring using the Python slice function, first create a slice object using the slice constructor.
🌐
DataCamp
datacamp.com › tutorial › python-slice
Python Slice: Useful Methods for Everyday Coding | DataCamp
January 15, 2025 - # Create a slice object slicer = slice(7, 14) # Apply the slice object print(text[slicer]) # Output: Slicing · Data parsing: Extract specific fields from structured text like CSV rows or log files. Text manipulation: Format strings by removing prefixes, suffixes, or unwanted characters. Lists and tuples are foundational Python data structures, and slicing them can simplify your work.
🌐
Programiz
programiz.com › python-programming › methods › built-in › slice
Python slice()
Online Python Online JavaScript ... Rust Online Scala Online Dart Online R Online Ruby ... The slice() function returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes)....
🌐
Python
docs.python.org › pl › 3.6 › c-api › slice.html
Slice Objects — Python 3.6.15 - dokumentacja
Usable replacement for PySlice_GetIndices(). Retrieve the start, stop, and step indices from the slice object slice assuming a sequence of length length, and store the length of the slice in slicelength. Out of bounds indices are clipped in a manner consistent with the handling of normal slices. Returns 0 on success and -1 on error with exception set. Zmienione w wersji 3.2: The parameter type for the slice parameter was PySliceObject* before. ... The Python Ellipsis object.