I am creating a list whose items are to be mapped by index number. I tried using the list.insert()
method. But still it always adds the first element to 0th index and I want the first element at 1st index. For example:
somelist=[]
somelist.insert(1,"Jack")
somelist.insert(2,"Nick")
somelist.insert(3,"Daniel")
>>print(somelist[1])
Nick # not Jack
how can I do this in Python? where I can insert element only at given index and let the list start from index 1.
When you insert something into a empty list, it will always be starting from the first position. Do something like this as workaround:
somelist=[]
somelist.insert(0,"dummy")
somelist.insert(1,"Jack")
somelist.insert(2,"Nick")
somelist.insert(3,"Daniel")
#print(somelist[1])
print(somelist[1])
output:
Jack
I think a dictionary could be helpful here if that will do.
Like
d={}
and insertion at required places is as easy as
d[1]="Jack"
d[2]="Nick"
d[3]="Daniel"
Now
print( d[1] )
will print
Jack
This way you won't have to use dummy values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With