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
🌐
W3Schools
w3schools.com › python › ref_func_slice.asp
Python slice() Function
Start the slice object at position 3, and slice to position 5, and return the result:
🌐
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.
Discussions

python - How to implement the lazy slicing of a class instance? - Stack Overflow
I am building a class which has underpinning it a list of ints, its __getitem__ method is then a reasonably computationally involved function outputting a list of potentially large size. Here is th... More on stackoverflow.com
🌐 stackoverflow.com
Alternative to create slice and tuple of slices with slice.__class_getitem__ - Ideas - Discussions on Python.org
Sometimes we want to use the same slice object with multiple objects, which needs to be explicitly created as: s = slice(start, stop) x[s], y[s] # equivalent to x[start:stop], y[start:stop] This becomes less readable for “multidimensional” objects, such as NumPy arrays: s = (Ellipsis, ... More on discuss.python.org
🌐 discuss.python.org
8
July 26, 2023
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
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
🌐
Python
docs.python.org › 3 › c-api › slice.html
Slice Objects — Python 3.14.6 documentation
Retrieve the start, stop and step indices from the slice object slice, assuming a sequence of length length.
🌐
Python Morsels
pythonmorsels.com › implementing-slicing
Implementing slicing - Python Morsels
March 27, 2023 - That way slicing ProxySequence ... >>> p = ProxySequence(string) >>> p[1:] ProxySequence('bcdefghi') Python's slicing syntax is powered by slice objects....
🌐
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.
🌐
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]
Find elsewhere
🌐
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.
🌐
Gaopinghuang0
gaopinghuang0.github.io › 2018 › 11 › 17 › python-slicing
Implementing slicing in __getitem__ · Gaoping Huang's Blog
November 17, 2018 - class Seq(object): def __init__(self, seq): self._seq = seq def get_value(self, i): pass def __getitem__(self, key): if isinstance(key, slice): start, stop, step = key.indices(len(self)) return Seq([self[i] for i in range(start, stop, step)]) elif isinstance(key, int): return self.get_value(key) elif isinstance(key, tuple): raise NotImplementedError, 'Tuple as index' else: raise TypeError, 'Invalid argument type: {}'.format(type(key)) http://docs.python.org/library/functions.html#slice
🌐
Programiz
programiz.com › python-programming › methods › built-in › slice
Python slice()
The slice() function returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).
🌐
Medium
medium.com › @beef_and_rice › mastering-pythons-getitem-and-slicing-c94f85415e1c
Mastering Python’s __getitem__ and slicing | by gyu-don | Medium
May 17, 2019 - Let us inspect colon separated slice. # As same as above part. class Inspector: def __getitem__(self, key): return keya = Inspector()
🌐
DataFlair
data-flair.training › blogs › python-slice
Python Slice Constructor - Python Slice String & Slicing Tuple - DataFlair
April 25, 2026 - This aids readability and implements abstraction. To slice an iterable, we use the slicing operator, that is [ ]. To separate the start, stop, and step values, we use the colon ( : ).
🌐
Mathspp
mathspp.com › blog › pydonts › inner-workings-of-sequence-slicing
Inner workings of sequence slicing | Pydon't 🐍 | mathspp
May 18, 2021 - It is strings that cannot handle the indices, and the extra slice, that you gave to the __getitem__ setting. Compare this with an actual SyntaxError: >>> for in range(10): File "<stdin>", line 1 for in range(10): ^ SyntaxError: invalid syntax · I couldn't even change lines to continue my make-believe for loop, Python outright complained about the syntax being wrong. However, in your custom objects, you can add support for multiple indexing/slicing: >>> class Seq: ...
Top answer
1 of 2
1

Instead of returning a generator, return a view. This is an object that conceptually represents the sequence of elements in question. We can do this by storing a reference to the original A instance, plus a range that encodes the instances. When we index into the view, we can ask the range which original index (or indices) are involved.

Supposing we set up the general structure:

class A(list):
    def __init__(self, n):
        super().__init__()
        self[:] = [i for i in range(0, n)]

    def _at(self, idx):
        # custom logic here to return the correct value for self[idx]

    def __getitem__(self, idx):
        if isinstance(idx, int):
            return self._at(idx)
        elif isinstance(idx, slice):
            # The `indices` method of a slice object converts to
            # start, stop, step values which we can use to construct a range.
            return A_view(self, range(*idx.indices(len(self))))
        else:
            raise TypeError # this is not an appropriate use for `assert`

Then our view could look like:

class A_view:
    def __init__(self, original, indices):
        self._original, self._indices = original, indices


    def __getitem__(self, idx):
        if isinstance(idx, int):
            return self._original[self._indices[idx]]
        elif isinstance(idx, slice):
            return A_view(self._original, self._indices[idx])
        else:
            raise TypeError

    def __len__(self):
        return len(self._indices)

The idea is that if we receive an integer index, we translate it through the range object into an index for the original A, and call back to its __getitem__ (with an integer this time). If we receive another slice, we use it to slice our range into a sub-range, and make another view.

Note that your A class should already be iterable, due to inheriting from list. To make the view iterable (and also get the in operator, forward and reverse iteration, .index and .count methods for free), you can inherit from collections.abc.Sequence. You just need a __getitem__ and __len__ - both easy to implement, as above - and the base class will do the rest (while also advertising to isinstance that your class has these properties).

2 of 2
1

I'm not totally sure what you're asking. Does this work for your use case? Items will be generated lazily and not stored (unless the caller stores them).

class LazyCollection:

    def __getitem__(self, key):
        if isinstance(key, int):
            return self.get_single_item(key)

        elif isinstance(key, slice):
            def my_generator():
                for index in slice_to_range(key):
                    yield self.get_single_item(index)
            return my_generator()


    def get_single_item(self, index):
        # (Example! Your logic here.)
        return index * 10


def slice_to_range(my_slice):
    '''
    More options for implementing this:

    https://stackoverflow.com/questions/13855288/turn-slice-into-range
    '''
    start = my_slice.start if my_slice.start is not None else 0
    stop = my_slice.stop
    step = my_slice.step if my_slice.step is not None else 1
    return range(start, stop, step)


coll = LazyCollection()

# Get a single item
print(coll[9999])

# Get a slice
for x in coll[2:10]:
    print(x)

Output:

99990
20
30
40
50
60
70
80
90
🌐
Python.org
discuss.python.org › ideas
Alternative to create slice and tuple of slices with slice.__class_getitem__ - Ideas - Discussions on Python.org
July 26, 2023 - Sometimes we want to use the same slice object with multiple objects, which needs to be explicitly created as: s = slice(start, stop) x[s], y[s] # equivalent to x[start:stop], y[start:stop] This becomes less readable for “multidimensional” ...
🌐
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 ...
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).

🌐
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.