Python offers many built-in functions and methods for list manipulation. Here are some methods of the built-in list class that help in modifying lists.
- index()– This function returns the index of first matched item from the list.
syntax:-
list_name.index(element)
e.g.,
l=[8, 12, 18, 22, 24, 30] l.index(18)
Output- 2
- append()– This function is used to add an element to the list at the end.
syntax:-
list_name.append(new_element)
e.g.,
l=[1, 2, 3, 4, 5] l.append(6) print(l)
Output- [1,2,3,4,5,6]
- extend()– This method is used to add multiple elements to a list.
syntax:-
list_name.extend(list to add)
e.g.,
l=[1,2,3,4,5] l1=[6,7,8] l.extend(l1) print(l)
Output- [1,2,3,4,5,6,7,8]
- insert()- The insert method is an insertion method for lists.
syntax:-
list.insert(index_number, element)
e.g.,
l=[1,2,3,4,5,6] l.insert(2,7) print(l)
Output- [1,2,7,3,4,5,6]
- pop()- It is used to remove the last element of the list. If the index is provided, then it will remove the element at the particular index.
syntax:-
list.pop()
e.g.,
l=[1,2,3,4,5,6,7,8] l.pop() print(l)
Output- 8 [1,2,3,4,5,6,7]
- reverse()-It is used to reverse the order of items in a list.
syntax:-
list.reverse()
e.g.,
l=[1,2,3,4,5,6,7,8,9] l.reverse() print(l)
Output- l=[9,8,7,6,5,4,3,2,1]
This is all about methods and function in list in python.