Implementing slicing in __getitem__

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. __getitem__ method can be implement in a class, and the behavior of slicing can be defined inside it.

Syntax:

__getitem__(slice(start, stop, step))

Parameter:

  • slice() : constructor to create slice object.
  • start: An integer number specifying start index.It is optional and default is 0.
  • stop: An integer number specifying end index.
  • step: An integer number specifying the step of slicing. It is optional and
    default is 1.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# abcde is string can be 
# an array as well.
sliced ='abcde'.__getitem__(slice(0, 2, 1)) 
print(sliced)

chevron_right


Output



ab

Explanation:
The string abcde is sliced with starting index 0 and stop index 2 with step index 1 hence it slices ab from the string and prints the output.

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

class Demo:
    def __getitem__(self, key):
          
        # print a[1], a[1, 2], 
        # a[1, 2, 3]
        print(key)
          
        return key
a = Demo()
  
# => slice 1
a[1]
  
# => slice(1, 2)
a[1, 2]
  
# => (1, 2, 3)
a[1, 2, 3]

chevron_right


Output

1
(1, 2) 
(1, 2, 3)

Explanation:
The class demo has the __getitem__ method, slicing is comma-separated. Key prints the sliced object which is passed in class through variable a.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.