How To Start Array Index From 1 In Python

In Python, the index of an array (or list) starts from 0 by default. However, in some situations, you may want to start the index from 1—for example, when you work with matrices or when the indices represent a real-world quantity.

In this tutorial, we’ll show you how to start an array index from 1 in Python by creating a custom data structure with your desired indexing behavior.

Step 1: Create a Custom List Class

We’ll start by creating a custom class that inherits from Python’s native list class. This custom class will be used to initialize your desired index offset (in this case, 1).

In the code snippet above, we define a class IndexList that inherits from Python’s native list class. The constructor method __init__ takes the start_index parameter, which defines the desired start index for the list. We are using super() to call the parent list class constructor method (__init__) with the arguments passed.

Step 2: Overriding Indexing Methods

Next, we need to override the native Python list indexing methods to incorporate our custom index offset. In this step, we’ll override methods __getitem__ and __setitem__:

Here, __getitem__ and __setitem__ are methods that are internally handling the list indexing behavior. By overriding them, we are modifying the index value with our custom offset before passing it to the respective parent methods using super().

Step 3: Test the Custom List Class

Now let’s create an instance of our custom IndexList class to see if it works as expected:

In this code, we create an instance of IndexList with a starting index of 1 and a given list of elements. We then print the elements of the list using our custom indexing and modify some values before printing the updated list.

Full Code


Original List: [10, 20, 30, 40, 50]
Element at index 1: 10
Element at index 5: 50
Modified List: [99, 20, 30, 40, 100]


In this tutorial, we demonstrated how to start an array index from 1 in Python by creating a custom list class that inherits from Python’s native list class and overrides its indexing methods. This custom class will allow you to use lists with custom indexing and provide better control while working with data structures.