How to change 0 based indexing to 1 based indexing in python..?? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to change 0 based indexing to 1 based indexing in python..?? (/thread-23907.html) |
How to change 0 based indexing to 1 based indexing in python..?? - Ruthra - Jan-22-2020 Python works in 0 based index. I have tried to change the python to work in 1 based index. python_file_A.py def __getitem__(self, index): return self.list[index-1] def __setitem__(self, index, value): self.list[index-1] = valuepython_file_B.py example_list=['a','b','c','d','e'] print("Before function change : ",example_list[1]) from python_file_A import * print("After function change : ",example_list[1])While running python_file_B.py, Actual Output : Before function change : b After function change : b Expected Output : Before function change : b After function change : a After function change the example_list[1] should give 'a' as output which is example_list[0] Without using class be preferred. Kindly help to resolve this. reference links below, https://stackoverflow.com/questions/11726866/make-array-index-1-instead-of-index-0-based http://defcraft.blogspot.com/2007/04/n-based-python-list.html RE: How to change 0 based indexing to 1 based indexing in python..?? - jefsummers - Jan-22-2020 For a function not in a class, remove the reference to self. General recommendation - wouldn't it be better to just remember that it is zero based? Using getters and setters is definitely un-pythonic, adds a layer for errors to creep in. RE: How to change 0 based indexing to 1 based indexing in python..?? - Ruthra - Jan-22-2020 (Jan-22-2020, 05:07 PM)jefsummers Wrote: For a function not in a class, remove the reference to self. python_file_A.py def __getitem__(index): return list[index-1] def __setitem__(index, value): list[index-1] = valuepython_file_B.py example_list=['a','b','c','d','e'] print("Before function change : ",example_list[1]) from python_file_A import * print("After function change : ",example_list[1])While running python_file_B.py, Actual Output : Before function change : b After function change : b Expected Output : Before function change : b After function change : a Removed the self (Actually self is not a real issue what i am seeking for). Even though the expected output is not coming. You can recommend other ways of doing it. |