In this article we are going to see about the various methods of the list data type. The 9 methods that we are going to see in this article are,
The append() methods adds a new element at the end of the list. The following code snippet explains this clearly.
Adding a new colour to the list adds it to the end.
The extend methods takes a list and adds it to another list combining them to a single list.
The extend methods add the elements of the second list to the first list combining them to a single list.
The insert method takes two arguments. The item to be added to the list and the position at which it has to be added. This is more suitable to use than append when we want to insert the element in a particular position.
This code snippet inserts value “2” at position “1”. Of course the index begins from 0.
The remove() method takes an element as input and removes if that element is present in the list otherwise it will return error if there is no such item in the list.
The pop method takes an index as argument and removes element from that index. If no index is given it will remove the last element from the list.
Here i have given the index value as 2, so the number at the index 2 which is 9 is removed.
In this code snippet no index is given in the pop method, so it pops the last element and returns it.
The index method takes an element as argument and returns the index of that element in the list.
In this code snippet i have given the value 9 as the argument and its index is returned which is 2.
The count method counts the number of times a particular element is present in the list. It takes the element as the argument.
Since the number 4 is present 3 times in the list, the count method returns 3.
The sort method can be used to sort the dictionary either in ascending or descending order.
The reverse method reverses the entire list. This is similar to list[::-1]
We can also reverse the list by simply doing [::-1] to the list. This will work for the strings as well.
Hope this was helpful.
Happy coding !