9

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.

9
  • list.inset() is not a "inser at an index" instead it is "insert before(or at) the index", somelist.insert(1,"Jack") will insert at first at index 0 because no eleemnt exists before 1 index Commented Dec 27, 2018 at 6:38
  • 1
    Keep somelist.insert(0,None) 0 index as None Commented Dec 27, 2018 at 6:39
  • @AnupYadav This works thanks! Commented Dec 27, 2018 at 6:43
  • 1
    Why would you not just index the list with n - 1 if your n is one based? Why are you really trying to shift the list elements? Commented Dec 27, 2018 at 6:50
  • 1
    instead of adding None at 0th index, better to change print(somelist[1]) to print(somelist[0]) Commented Dec 27, 2018 at 6:54

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

This is much better than using dummy elements, which make a list much less iterable.
1

Your somelist array is empty, which means you can't add an item to the index 1 if there is no item in index 0..

With this i mean when you first try to insert "Jack" to index 1, it goes automatically to index 0, and then you insert "Nick" to index 2, and that goes to index 1... and last you print index 1 which is "Nick"

3 Comments

so should I initialize it with some item?
Remember that the first item in an array is index 0
@MrAlpha Depends, You must first learn what the insert() method do

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.