How to insert an object in a list at a given position in Python?

PythonServer Side ProgrammingProgramming

If you want to insert an element at a given position, use the insert(pos, obj) method.  It accepts one object and adds that object at the position pos of the list on which it is called. 

example

my_list = [2, 3, 1, -4, -1, -4]
my_list.insert(1, 0)
print(my_list)

Output

This will give the output −

[2, 0, 3, 1, -4, -1, -4]

If you want to insert an object at the end only, then use append instead of insert. It accepts one object and adds that object to the end of the list on which it is called. 

example

my_list = [2, 3, 1, -4, -1, -4]
my_list.append(0)
print(my_list)

Output

This will give the output −

[2, 3, 1, -4, -1, -4, 0]
raja
Published on 05-Jan-2018 14:37:45
Advertisements