DEV Community

Keerti Sadana S
Keerti Sadana S

Posted on Edited on

PYTHON - APPEND(),INSERT() AND EXTEND()

Append:
The append() method in Python is used to add a single element to the end of a list.

Example:

l=[]
l.append('abcd')
l.append(1234)
l.append(True)
l.append(5.4)
print(l)
Enter fullscreen mode Exit fullscreen mode

Output:
['abcd', 1234, True, 5.4]

Insert:
-> To insert an item at a specific position in a Python list, use the list.insert(index, element) method.
-> This method modifies the original list in place and does not return a new list.

Example:

l = ['abcd',1234,True, 5.4]

l.insert(1, 'dhanush')
print(l)

l.insert(-2, 'vinoth m')
print(l)

l.insert(-101, 'akilan')
print(l)
Enter fullscreen mode Exit fullscreen mode

Output:
['abcd', 'dhanush', 1234, True, 5.4]
['abcd', 'dhanush', 1234, 'vinoth m', True, 5.4]
['akilan', 'abcd', 'dhanush', 1234, 'vinoth m', True, 5.4]

Nested list:

q = [90,87,65,67,89]
h = [96,97,95,69,99]
a = [99,98,100,76,49]

marks = [q,h,a]
print(marks)
Enter fullscreen mode Exit fullscreen mode

Output:
[[90, 87, 65, 67, 89], [96, 97, 95, 69, 99], [99, 98, 100, 76, 49]]

Extend():
-> The extend() method is used to add all elements from another iterable to the end of a list.
-> It updates the original list by adding each element one by one.

l2 = []
l2.extend('pqrs')
print(l2)
Enter fullscreen mode Exit fullscreen mode

Output:
['p', 'q', 'r', 's']

Append VS Insert VS Extend:

Top comments (0)