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

Use with AIsl = slice(0,4)

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

Use with AI>>> 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.

Use with AIdata = """\
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:

Use with AIid : 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.15.2 documentation
The type object for slice objects. This is the same as slice in the Python layer.
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:

Use with AIsl = slice(0,4)

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

Use with AI>>> 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.

Use with AIdata = """\
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:

Use with AIid : 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:

Use with AI>>> "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:

Use with AIdef __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).

๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ methods โ€บ built-in โ€บ slice
Python slice() | Programiz
March 14, 2024 - In this tutorial, we will learn about the Python slice() function with the help of examples. The slice() function returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).
๐ŸŒ
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 - Creates a slice object that specifies how to slice sequences like strings, lists, tuples, and ranges
๐ŸŒ
The Python Coding Stack
thepythoncodingstack.com โ€บ notes from the near future โ€บ a slicing story
A Slicing Story - The Python Coding Stack
September 24, 2023 - But sometimes you may want to name a slice you want to re-use in your code. Since a slice is an object, just like most other things in Python, you can create a slice instance and assign it to a name.
Find elsewhere
๐ŸŒ
DataCamp
datacamp.com โ€บ home โ€บ tutorials โ€บ python โ€บ python slice: useful methods for everyday coding
Python Slice: Useful Methods for Everyday Coding | DataCamp
January 15, 2025 - Pythonโ€™s slice() function provides an alternative definition of slicing parameters as reusable slice objects.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ implementing-slicing
Implementing slicing - Python Morsels
August 3, 2026 - You can make Python objects support slicing by implementing a __getitem__ method that accepts slice objects.
๐ŸŒ
Towards Data Science
towardsdatascience.com โ€บ home โ€บ data science โ€บ slicing in python: a comprehensive guide
Slicing in Python: A Comprehensive Guide | Towards Data Science
June 5, 2024 - When you use sequence[start:stop:step], Python calls sequence.__getitem__(slice(start, stop, step)). As you see, the range is converted into a so-called slice object.
๐ŸŒ
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.
Top answer
1 of 16
6670

The syntax is:

Use with AIa[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

There is also the step value, which can be used with any of the above:

Use with AIa[start:stop:step] # start through not past stop, by step

The key point to remember is that the :stop value represents the first value that is not in the selected slice. So, the difference between stop and start is the number of elements selected (if step is 1, the default).

The other feature is that start or stop may be a negative number, which means it counts from the end of the array instead of the beginning. So:

Use with AIa[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

Similarly, step may be a negative number:

Use with AIa[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

Relationship with the slice object

A slice object can represent a slicing operation, i.e.:

Use with AIa[start:stop:step]

is equivalent to:

Use with AIa[slice(start, stop, step)]

Slice objects also behave slightly differently depending on the number of arguments, similar to range(), i.e. both slice(stop) and slice(start, stop[, step]) are supported. To skip specifying a given argument, one might use None, so that e.g. a[start:] is equivalent to a[slice(start, None)] or a[::-1] is equivalent to a[slice(None, None, -1)].

While the :-based notation is very helpful for simple slicing, the explicit use of slice() objects simplifies the programmatic generation of slicing.

2 of 16
729

The Python tutorial talks about it (scroll down a bit until you get to the part about slicing).

The ASCII art diagram is helpful too for remembering how slices work:

Use with AI +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5
  -6  -5  -4  -3  -2  -1

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n.

๐ŸŒ
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, ...
๐ŸŒ
Bas
bas.codes โ€บ posts โ€บ python-slicing
A Comprehensive Guide to Slicing in Python - Bas codes
January 31, 2022 - Since weโ€™re using Nones, the slice object needs to calculate the actual index values based on the length of our sequence. Therefore, to get our index triple, we need to pass the length to the indices method, like so: ... This will give us the triple (0, 6, 2). We now can recreate the loop like so: sequence = list("Python") start = 0 stop = 6 step = 2 i = start while i != stop: print(sequence[i]) i = i+step
๐ŸŒ
DataFlair
data-flair.training โ€บ blogs โ€บ python-slice
Python Slice Constructor - Python Slice String & Slicing Tuple - DataFlair
April 25, 2026 - The slice() is a constructor that creates a Python Slice object to represent the set of indices that range(start, stop, step) specifies.
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
How to Slice a List, String, and Tuple in Python | note.nkmk.me
May 6, 2023 - In Python, by using a slice (e.g., [2:5:2]), you can extract subsequences from sequence objects, such as lists, strings, tuples, etc. Basic usage of slices[start:stop][start:stop:step] [start:stop] [s ...
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-use-the-slice-method-in-python
How to use the slice() method in Python
The slice method in Python returns a slice object. This object contains a list of indices specified by a range.