Insert a new element in first position in a python list

Published: January 07, 2019

DMCA.com Protection Status

To insert a new element in first position in a python list , there is the insert():

>>> l = ['b','c','d','e','f']
>>> l.insert(0,'a')
>>> l
['a', 'b', 'c', 'd', 'e', 'f']

This method can also be used to insert an element in any position in the list:

>>> l = ['a','b','d','e','f']
>>> l.insert(2,'c')
>>> l
['a', 'b', 'c', 'd', 'e', 'f']

Another example using index():

>>> l = ['a','b','d','e','f']
>>> l.insert(l.index('b')+1,'c')
>>> l
['a', 'b', 'c', 'd', 'e', 'f']

References

Links Site
insert() python doc
Insert at first position of a list in Python stackoverflow
index() programiz