How To Insert A Element At Specific Index In Python List
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 fi
Solution 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
Solution 2:
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.
Solution 3:
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"
Post a Comment for "How To Insert A Element At Specific Index In Python List"