Friday, 4 December 2015

Python: insert: Insert an element at given position

List provides ‘insert’ method to insert an element at given position.

Syntax
list.insert(i, x)

list.insert(0, x) : Insert element x at front of list.
list.insert(len(list), x) : Insert element x at the end of the list.
list.insert(2, x) : Insert element x at 2nd position.


test.py
list=[2, 4, 6]
print(list)

list.insert(0, -2)
print(list)

list.insert(len(list), 8)
print(list)

list.insert(2, 3)
print(list)

$ python3 test.py
[2, 4, 6]
[-2, 2, 4, 6]
[-2, 2, 4, 6, 8]
[-2, 2, 3, 4, 6, 8]




Previous                                                 Next                                                 Home

No comments:

Post a Comment