Introduction
In my previous article,
Introduction to Python List, I explained the basics of lists and a few methods such as Index(), Append(), and Extend(). Now, let us understand the remaining List methods.
INSERT
The Insert method is used to insert an element into a list. It accepts two parameters, i.e.,
- The index which specifies the index of an element where you want to insert an element.
- Element is an element that you want to insert into the list.
Syntax- list.insert (index,element)
Example
- l=[2,4,6]
- l.insert(2,14)
- print(l)
Note
It accepts only two parameters; otherwise, it generates an error.
POP
This method is used to delete an element from the list from the end. It takes an index as an optional parameter. That is, if you don't pass any argument then it will remove the item from the end of the list; otherwise, it will remove the item from the specified position.
Syntax- list.pop()
list.pop(index)
- l=[2,3,8,7,9,6,5]
- l.pop()
- print(l)
- l.pop(3)
- print(l)
REMOVE
This method is used to delete an element from the List. However, it is different from the pop() method. Instead of deleting an element from the index, it will delete an element as per argument. That is, we can pass an element as an argument to be deleted.
Syntax- list.remove(element)
- l=[2,3,8,7,9,6,5]
- l.remove(3)
- print(l)
Note
If the element is not present in the list, then it will generate an error.
CLEAR
This method is used to clear the whole list, i.e., it removes all the items from the list.
Syntax- list.clear()
- l=[2,3,8,7,9,6,5]
- l.clear()
- print(l)
REVERSE
We can reverse the order of items in a list by using this method.
Syntax- list.reverse()
- l=[2,3,8,7,9,6,5]
- l.reverse()
- print(l)
SORT
This method is used to sort a list. By default, the list is sorted in ascending order. We can also sort a list in descending order, bypassing "reverse=True" as an argument in sort().
Syntax- list.sort() // Ascending order
list.sort(reverse=True) // Descending order
- l=[2,3,8,7,9,6,5]
- l.sort()
- print(l)
- l.sort(reverse="True")
- print(l)
COUNT
This method will return the number of times the element occurs within a specified list. It takes one argument, as an element to be counted.
Syntax- list.count(element)
- l=[2,3,8,3,7,9,3,6,5]
- l.count(3)
- print(l)
Summary
In this article, we discussed all the methods of List. I hope this will help the readers to understand how to use and implement Lists in Python.
Feedback or queries related to this article are most welcome. Thanks for reading.