Lists are mutable, meaning that elements of lists can be changed once they have been assigned to variables. We can change an element in a list, we can delete an entire list, and we can add and remove one element from a list after assigning it to a variable.
Adding an element to a list can be done in a number of ways:
list.append()
:
This method adds the element at the end of the list.a = [25,"vinay",45,217]a.append("rohit")print(a)
list.extend()
:
This method adds more than one element to the list.b = [2,45,101]b.extend(["sunny","sandeep","shashanka"])print(b)
insert(index, element)
:
This method adds the element in the list at any index.
c = [2,4,"vik",76]c.insert(0,"python")print(c)
Removing an element from a list can be done in a number of ways:
list.pop()
:
This method removes the last element from the list.d = [12,34,56,78,89,0]d.pop()print(d)
list.pop(index)
If the index is mentioned, it removes the mentioned item from the list.e = [2,4,'vik',76]e.pop(2)print(e)
list.clear()
This deletes all elements in the list. The list is then called an empty list.f = [2,4,"data ",45,217,"structure"]f.clear()print(f)