Python Forum

Full Version: How to change 0 based indexing to 1 based indexing in python..??
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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] = value
python_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/1172...ex-0-based
http://defcraft.blogspot.com/2007/04/n-b...-list.html
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.
(Jan-22-2020, 05:07 PM)jefsummers Wrote: [ -> ]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.

python_file_A.py
def __getitem__(index):
  return list[index-1]
def __setitem__(index, value):
  list[index-1] = value
python_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.