The __getitem__() method will receive a slice object when the object is sliced. Simply look at the start, stop, and step members of the slice object in order to get the components for the slice.

>>> class C(object):
...   def __getitem__(self, val):
...     print val
... 
>>> c = C()
>>> c[3]
3
>>> c[3:4]
slice(3, 4, None)
>>> c[3:4:-2]
slice(3, 4, -2)
>>> c[():1j:'a']
slice((), 1j, 'a')
Answer from Ignacio Vazquez-Abrams on Stack Overflow
🌐
Python
docs.python.org › 3 › c-api › slice.html
Slice Objects — Python 3.15.2 documentation
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.
🌐
Python Morsels
pythonmorsels.com › implementing-slicing
Implementing slicing - Python Morsels
August 3, 2026 - When you slice a sequence, Python creates a slice object that it then passes to that sequence's __getitem__ method: ... It's a little bit unusual to call the slice class yourself, but it is possible, since slice is just a built-in class in Python:
Discussions

python - Implementing slicing in __getitem__ - Stack Overflow
I am trying to implement slice functionality for a class I am making that creates a vector representation. I have this code so far, which I believe will properly implement the slice but whenever I do something like v[4] where v is a vector, python raises an error about not having enough arguments. More on stackoverflow.com
🌐 stackoverflow.com
How can I use Python built-in slice object? - Stack Overflow
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 ... More on stackoverflow.com
🌐 stackoverflow.com
November 19, 2011
What does the slice() function do in Python? - Stack Overflow
When should one use the slice() function when programming in plain Python (without NumPy or SciPy)? Any examples will be appreciated. ... It is actually a class, which returns a slice object. More on stackoverflow.com
🌐 stackoverflow.com
A rectangular jigsaw puzzle generator made with python. Criticism and suggestions are welcome.
🌐 r/Python
11
24
February 2, 2021
🌐
Devcamp
bottega.devcamp.com › full-stack-development-javascript-python › guide › working-slice-class-python-store-slices
Working with the slice Class in Python to Store Slices
But there are times where you may not know or you may not want to hard code in this slice range. And so in cases like that Python actually has a special class called slice which we can call and store whatever these ranges we want are and what they're going to be.
🌐
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.
🌐
Programiz
programiz.com › python-programming › methods › built-in › slice
Python slice() | Programiz
March 14, 2024 - Note: We can use slice with any object which supports sequence protocol (implements __getitem__() and __len()__ method).
🌐
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
Find elsewhere
🌐
Python Central
pythoncentral.io › how-to-slice-custom-objects-classes-in-python
How to Slice Custom Objects/Classes in Python | Python Central
December 29, 2021 - [python] class MyDictStructure(Sequence): def __init__(self): # New dictionary this time self.data = {} ... def __getitem__(self, sliced): slicedkeys = self.data.keys()[sliced] data = {k: self.data[k] for key in slicedkeys} return data [/python]
🌐
DataFlair
data-flair.training › blogs › python-slice
Python Slice Constructor - Python Slice String & Slicing Tuple - DataFlair
April 25, 2026 - Let’s take a simple example of Python Slicing. ... Note that it displays values at the indices 0, 1, and 2. It stops at index 3. We can slice a string in Python using the Python slice() method.
🌐
The Python Coding Stack
thepythoncodingstack.com › notes from the near future › a slicing story
A Slicing Story - The Python Coding Stack
September 24, 2023 - 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.
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).

🌐
GeeksforGeeks
geeksforgeeks.org › python › implementing-slicing-in-__getitem__
Implementing slicing in __getitem__ - GeeksforGeeks
March 26, 2020 - The __getitem__ method is used for accessing list items, array elements, dictionary entries etc. slice is a constructor in Python that creates slice object to represent set of indices that the range(start, stop, step) specifies.
🌐
Mathspp
mathspp.com › blog › pydonts › inner-workings-of-sequence-slicing
Inner workings of sequence slicing | Pydon't 🐍 | mathspp
May 18, 2021 - Recall that “dunder” is short for “double underscore”, the common name that Python gives to methods that start and end with two underscores, which generally indicate that the method has to do with the inner workings of Python. We have seen other dunder methods in the Pydon'ts about str and repr and about Truthy, Falsy, and bool. The __getitem__ dunder method is the method that is called, behind the scenes, when you try to access indices or slices. An empirical verification of this is very easy to perform: we'll just create a new class, called S, that will be wrapping the built-in strings, and intercept the __getitem__ call:
🌐
Real Python
realpython.com › ref › builtin-functions › slice
slice() | Python’s Built-in Functions – Real Python
Returns a slice object that can be used to extract a portion of a sequence. Since Python 3.12, slice objects are hashable, provided that start, stop, and step are hashable, so they can be dictionary keys or set members.
🌐
Gaopinghuang0
gaopinghuang0.github.io › 2018 › 11 › 17 › python-slicing
Implementing slicing in __getitem__ · Gaoping Huang's Blog
November 17, 2018 - >>> class A(object): ... def __getitem__(self, key): ... print key ... >>> a = A() >>> a[0] 0 # an integer >>> a[0:2] slice(0, 2, None) # a slice object >>> a[0:4:2] slice(0, 4, 2) # a slice object of (start, stop, and step) >>> a[0,4,2] (0, 4, 2) # a tuple as index, which is out of our scope today
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › methods › built-in › slice › python-slice
Python slice() function | What is a slice function in Python? |
July 14, 2021 - The slice object is used to specify how to slice the sequence of data. Python slice() is a pre-defined function that is used to extract a subset of data elements or a subpart of data values that are stored in strings, tuples, lists, etc.
🌐
The Teclado Blog
blog.teclado.com › python-slices
Python Slices - The Teclado Blog
April 7, 2019 - We can define a slice object creating an instance of the slice class, which has three parameters: a starting index, a stopping index, and an optional step value.
🌐
DataCamp
datacamp.com › home › tutorials › python › python slice: useful methods for everyday coding
Python Slice: Useful Methods for Everyday Coding | DataCamp
January 15, 2025 - As I said, slicing is a core feature in Python, allowing developers to extract portions of sequences like lists, strings, and tuples. Python offers two primary ways to slice sequences without importing anything: the slicing : syntax and the slice() function.