Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to insert a element at specific index in python list

Tags:

python

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.

like image 880
Noob Avatar asked Dec 27 '18 06:12

Noob


2 Answers

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
like image 120
Jim Todd Avatar answered Sep 18 '22 17:09

Jim Todd


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.

like image 36
J...S Avatar answered Sep 22 '22 17:09

J...S