Python List Methods

We will discuss various Python List Methods with examples. A list in Python is a collection of ordered items, which can be of different types. The list Data structure in Python is implemented using the List class. The Python List class provides several Python methods.

1. Python List Methods

Below are methods that are defined in the python list class. Besides these, you can also use some of the python built-in functions to operate on the list.

Python List MethodsDescription
append()Add an element to the end of the list.
insert()Adds an element at the specified position.
extend()Add the elements of a list (or any iterable), to the end of the current list.
pop()Removes the element at the specified position.
remove()Removes the first item with the specified value.
clear()Remove all items from the list.
copy()Returns a shallow copy of the list.
reverse()Reverses the order of the list.
sort()Sorts the list in ascending or descending order.
count()Returns the number of elements with the specified value.
index()Returns the index of the first element with the specified value.
Python List Methods

2. append() – Add Element to List

The append() method adds an element to the end of the list. This method modifies the original list in place, meaning that it adds a new element to the list and does not return a new list.

The method takes one argument, which is the element that you want to add to the list. The element can be of any data type, including other lists, strings, numbers, etc.


# Syntax 
my_list.append(element)

# Example
my_list = ["python", "java"]
my_list.append("c++")
print(my_list)
 
# Output: 
# ["python", "java", "c++"]

3. insert() – Insert Element at Index

If you want to insert an element in a specific position, use the insert() method. This method in Python allows adding an element at a specific index in a list.

The method takes two arguments. Below is the syntax of the insert() method:


# Syntax
my_list.insert(index, value)

Here’s an example of how you might use the insert() method:


# Adding 'c++' at index 1
my_list.insert(1, "c++")
print(my_list) 

# Output:
#["python", "c++", "java"]

4. extend() – Extend the Existing List with Iterable

The extend() methods allow adding the elements of an iterable to the end of an existing list. The iterable can be as string, list, or tuple. It takes one argument, which is an iterable object containing the elements that you want to add to the list.


# Adding elements of list to the end of the my_list
my_list.extend(["c++", "go"])
print(my_list) 

# Output:
# ["python", "java", "c++", "go"]

# Extending list with Tuple
my_list.extend(("c++", "go"))
print(my_list) 

# Output:
# ["python", "java", "c++", "go"]

5. pop() – Remove Element at Specified Index

If you want to remove an element at a specified index from the python list you can use the pop() method. It is used to remove an element from a list at a specific index and return the removed element.

The default index of the pop() method is -1, meaning that if no index is provided as an argument, the method will remove and return the last element in the list by default.


# Pop element
removed_element = my_list.pop()
print(removed_element) 
print(my_list) 

# Output: "c++"
# Output: ["python", "java"]

# Pop anotehr element
removed_element = my_list.pop(1)
print(removed_element) 
print(my_list) 

# Output: "java"
# Output: ["python", "c++"]

6. remove() – Remove First Matching Value

The remove() method is used to remove the first occurrence of a specified element from a list. It will raise a ‘ValueError’ exception. So make sure to handle the exception.

The method takes one argument, which is the element you want to remove from the list. The element can be of any data type, including other lists, strings, numbers, etc.


# Remove element from list
my_list.remove("python")
print(my_list) 

# Output: 
# ["java", "c++", "python"]

# More safer method
try:
    my_list.remove("go")
except ValueError:
    print("element not in list")

7. clear() – Remove All Items from List

The clear() method is used to remove all the items from a list. It is a quick way of erasing all the contents of a list, leaving it empty and ready to be used again.


# Clear all elements
my_list.clear()
print(my_list) 

# Output: []

The are other ways for removing all items from a list. Among them, the del keyword and the remove() function is more common. Let’s have a look at the comparison between the three.

MethodDescriptionTime Complexity
my_list.clear()Empties the list by removing all elements from the list. Modifies the original list in place.O(n)
del my_listDeletes the reference to the list, making it inaccessible. Does not modify the original list.O(1)
for item in my_list: my_list.remove(item)Removes all elements from the list by iterating over it and calling the remove() method on each item.O(n^2)
Comparison of del, clear()and remove()

8. reverse() – Reverse the Order of List

Have you ever wondered to reverse the order of a list in python? The reverse() method allows you to reverse the order of the elements in a list.

The method does not take any arguments and modifies the list in place, meaning it does not return a new list.


# Reverse the list
my_list.reverse()
print(my_list) 

# Output: 
# ["python", "c++", "java", "python"]

9. copy() – Copy a List to Another List

The copy() list copy the reference of one list to another. This is called a shallow copy. A shallow copy is a new list that contains references to the same objects as the original list.

When you make a copy of a list, any changes made to the copy will also be reflected in the original list and vice versa.


# Copy list
copy_list = my_list.copy()
copy_list[0] = "javascript"
print("Original List: ", my_list)
print("Copy List: ", copy_list)

# Output:
# Original List:  ['python', 'java']
# Copy List:  ['javascript', 'java']

From the above example, it seems like the copy function work perfectly but it is not if you get the nested list in it. You can use the copy module in python to do the deep copy of a list.


# Using copy module
import copy
my_list = ["python", "java"]
deep_copy_list = copy.deepcopy(my_list)

10. sort() – Sort a List in Python

The list.sort() method sorts a list in place, meaning that it rearranges the list elements so that they are in ascending order.

The sort() method takes an optional key parameter, which can be used to specify a function to be called on each element of the list before sorting. By default, the sort() method arranges the element in ascending order. But If, the sort method sorts the list in descending order.


# Sort list in ascending order
my_list.sort()
print(my_list)

# Output:
# ["c++", "java", "python"]

# Sort list in descending order
my_list.sort(reverse=True)
print(my_list)

#Output:
#["python", "java", "c++"]

11. count() – Find Frequency of Element in List

To Find the number of times a specific element appears in a list, use the list.count() method. The count() method takes a single argument, which is the element for which you want to find the count. It returns the number of occurrences of that element in the list.


# Count frequency
count = my_list.count("python")
print(count)

# Output is 2 because the list have two 'Python'
# 2

12. index() – Find Index of Value in List

You can use the list.index() method to find the index of a specific value in a python list. The index() method takes a single argument, which is the element for which you want to find the index.

It returns the index of the first occurrence of that element in the list. If the provided element is not found within the range it throws an error ValueError.


# Find index of value
index = my_list.index("java")
print(index)

# Output:
# 1

It also takes the second argument for the starting index. If you pass the starting index it will check the list of elements coming after that index.


# Find index of a value
index = my_list.index("python", 2)
print(index)

# Output:
# 3

13. Conclusion

You have now learned all the methods of lists in python. We have provided a self-explanatory example of every list method. I hope you have now a clear understanding of list methods. Let me know if you have any questions.

AlixaProDev

I am a software Engineer with extensive 4+ years of experience in Programming related content Creation.

Leave a Reply