List methods in Python
Introduction
In Python, lists come in handy when we want to pack some items in a single variable. Lists are one of the four data types, that are used to store data in Python. Other data types in Python are Tuples, Sets and Dictionaries, all these data types have different usage. Lists are created using square brackets “[ ]”.
l = ["A", "B", "C"] ['A', 'B', 'C'] |
Types of Function
In List, there are multiple functions with which we can operate on lists, let us see all of them one by one.
append()
This method is to add an element at the end of an existing list.
Code
# list created |
Output
['A', 'B', 'C'] |
clear()
This function is used to remove all the elements present in the list. This method without creating any copy of the list empties the list.
Code
l = ['A', 'B', 'C'] |
Output
[] |
count()
Suppose we are working on a list and we want to count the number of times an element is present in the list. So to do this we can use the count() method to get the number of times an element is present in the list.
Code
l = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b'] |
Output
3 |
insert()
In Python, if we want to add an element to a certain index then we can use the insert(0 methods.
Code
l = ['A', 'C'] |
Output
['A', 'B', 'C'] |
remove()
In Python, if we want to delete an element from the list, then we can use the remove() function.
Code
l = [ 'a', 'b', 'c', 'd' ] |
Output
['a', 'b', 'd'] |
pop()
In Python, pop() is a method that removes the last element in the list and also returns it. This method also can remove the element of the desired index and returns it. The difference between pop() and remove() is that remove() just deletes the element whereas the pop() method removes and returns the removed element.
Code
l = ['A', 'B', 'C', 'D'] |
Output
Popped element: D |
reverse()
In Python, if we are required to reverse the elements of the list, then we can do so by using the reverse() method. With this method, the elements of the list reverse in place. This method doesn’t copy the list that is it does not use any extra pace but just makes changes in the list itself.
Code
l = [1, 2, 3, 4] |
Output
[4, 3, 2, 1] |
sort()
In Python, the sort(0 functions is used when we need to arrange the list in a certain order or a user-defined order. In all cases, the time complexity come is O(In Pythnlogn) in python.
Code
l = [1, 3, 4, 2] |
Output
[1, 2, 3, 4] |