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.
__getitem__(slice(start, stop, step))
- 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.
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.
1 (1, 2) (1, 2, 3)
The class demo has the
__getitem__ method, slicing is comma-separated. Key prints the sliced object which is passed in class through variable a.
- Interesting facts about strings in Python | Set 2 (Slicing)
- Python List Comprehension and Slicing
- String slicing in Python to check if a string can become empty by recursive deletion
- Basic Slicing and Advanced Indexing in NumPy Python
- Python Slicing | Reverse an array in groups of given size
- String slicing in Python to rotate a string
- Program to cyclically rotate an array by one in Python | List Slicing
- Python Slicing | Extract ‘k’ bits from a given position
- Python | Slicing list from Kth element to last element
- Python | Variable list slicing
- Python | Alternate range slicing in list
- Python | Get the substring from given string using list slicing
- Python | Reverse Slicing of given string
- Python | Custom slicing in List
- Python | K elements Slicing
- String Slicing in Python
- Python | Custom List slicing Sum
- Python | Reverse Interval Slicing String
- Python | Reverse Incremental String Slicing
- Slicing range() function in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.