Home > Software engineering >  Python index starts at 0. Any possibility to set index value as 1 for any terminal?
Python index starts at 0. Any possibility to set index value as 1 for any terminal?

Time:11-09

I am porting the Matlab code to Python. In Matlab, indices start at 1, but in python, they start at 0. Is there any way to set the first index as 1 through a command line flag?

It will be very useful for programming during index iteration.

CodePudding user response:

No, there's no way to do this. Python is a 0-indexed language. Guido Van Rossum (Python creator) explained his reasons behind selecting 0-indexing over 1-indexing in this blog post:

http://python-history.blogspot.com/2013/10/why-python-uses-0-based-indexing.html

CodePudding user response:

As far as Python is concerned, there cannot be changes in the Indexing part. It always starts with 0 (Zero) only and progresses onwards. Hope this helps you.

CodePudding user response:

Actually, starting from 0 is easier for all computer-related tasks - it is just that mathematical notation, as inherited by matlab starts at 1.

For compatibility and ease-to-port code, I think you could write some special cased classes that would modify the indexes in access-time, so that one won't have to worry about changing indexes at a first porting-pass (but I'd drop those and revert to 0-indexed structures in a second pass).

You would have to use those special-purposed data structures instead of the built-in lists and tuples - and, when moving to n-dimensional arrays, in numpy code, it might become simply to hard to be worth it to have the " 1" data structures working, as there are lots of corner cases with multi-dimensional indexes.

For plain lists though, you can have a displaced list by just re-writting the __getitem__, __setitem__ and __delitem__ methods.

class MatList(list):
 
   def __getitem__(self, index):
       return super().__getitem__(index - 1)
   def __setitem__(self, index, value):
       return super().__setitem__(index - 1, value)
   def __delitem__(self, index):
       return super().__delitem__(index - 1)

Add more methods as needed (.index for example, or .pop)

CodePudding user response:

Ah, after some research I found the solution. This is doable, but I don't recommend it. You can subclass list and then replace list with your new wrapper. Like this:

class ListWrapper(list):
    def __getitem__(self, index):
        return super().__getitem__(index-1)


list = ListWrapper

lst = ListWrapper([1, 2, 3])
print(lst[2])  # => 2

This is only part of the solution though. You'll need to add more methods to change the index as you use them. For example, you'll need to make wrappers for __setitem__() and __delitem__().

CodePudding user response:

i'm not aware of whether you can change that by default. But you can specify the starting and ending indexes for loops with range, enumerate, etc. e.g.

for i in range(1, end   1):
  • Related