Open In App

Ways to remove particular List element in Python

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

List is an important container and is used almost in every code of day-day programming as well as web development. The more it is used, more is the required to master it and hence knowledge of its operations is necessary. Let’s see the different ways of removing particular list elements. 

Method #1 : Using remove() remove() can perform the task of removal of list element. Its removal is in place and does not require extra space. But the drawback that it faces is that it just removes the first occurrence from the list. All the other occurrences are not deleted hence only useful if the list doesn’t contain duplicates. 

Python3




# Python code to demonstrate
# element removal in list
# using remove() method
 
test_list1 = [1, 3, 4, 6, 3]
test_list2 = [1, 4, 5, 4, 5]
 
# Printing initial list
print("The list before element removal is : "
      + str(test_list1))
 
# using remove() to remove list element3
test_list1.remove(3)
 
# Printing list after removal
# only first occurrence deleted
print("The list after element removal is : "
      + str(test_list1))


Output:

The list before element removal is : [1, 3, 4, 6, 3]
The list after element removal is : [1, 4, 6, 3]

Time complexity: O(n), where n is the length of the list test_list1. 

Auxiliary space complexity: O(1). The space used by the algorithm does not increase with the size of the input list

Method #2 : Using set.disard() set.disard() 

It can perform the task of removal of list element. Its removal is inplace and does not require extra space. List is first converted to set, hence other duplicates are removed and also list ordering is sacrificed. Hence not a good idea when we need to preserve ordering or need to keep duplicates. 

Python3




# Python code to demonstrate
# element removal in list
# using discard() method
 
test_list1 = [1, 3, 4, 6, 3]
test_list2 = [1, 4, 5, 4, 5]
 
# Printing initial list
print("The list before element removal is : "
      + str(test_list2))
 
# using discard() to remove list element 4
test_list2 = set(test_list2)
test_list2.discard(4)
 
test_list2 = list(test_list2)
 
# Printing list after removal
# removes element as distinct initially
print("The list after element removal is : "
      + str(test_list2))


Output :

The list before element removal is : [1, 4, 5, 4, 5]
The list after element removal is : [1, 5]

Method #3 : Using Lambda Function + filter()

Lambda functions have always been a useful utility and hence can be used to perform tough task in just 1 liners. These can also perform this particular task. Drawback is that they are not inplace and require extra space or requires a overwrite. It actually constructs a new list, and filters out all of the required elements. It removes all the occurrences of element. 

Python3




# Python code to demonstrate
# element removal in list
# using filter() + Lambda function
 
test_list1 = [1, 3, 4, 6, 3]
test_list2 = [1, 4, 5, 4, 5]
 
# Printing initial list
print("The list before element removal is : "
      + str(test_list1))
 
# using filter() + Lambda function
# to remove list element 3
test_list1 = list(filter(lambda x: x != 3, test_list1))
 
# Printing list after removal
print("The list after element removal is : "
      + str(test_list1))


Output:

The list before element removal is : [1, 3, 4, 6, 3]
The list after element removal is : [1, 4, 6]

Method #4: Using List Comprehension 

List comprehensions are easier method to perform the similar task as performed by lambda function. It has the same drawback of not being inplace and also requires extra space or overwrite. It is better in a way that filter() is not required to perform it. It removes all the occurrences of element. 

Python3




# Python code to demonstrate
# element removal in list
# using List Comprehension
 
test_list1 = [1, 3, 4, 6, 3]
test_list2 = [1, 4, 5, 4, 5]
 
# Printing initial list
print("The list before element removal is : "
      + str(test_list2))
 
 
# using List Comprehension
# to remove list element 4
test_list2 = [x for x in test_list2 if x != 4]
 
# Printing list after removal
print("The list after element removal is : "
      + str(test_list2))


Output :

The list before element removal is : [1, 4, 5, 4, 5]
The list after element removal is : [1, 5, 5]

 Method #5: Using pop() Using pop method with list index to pop element out of list 

Approach:

  1. Define a list named test_list1 containing some elements.
  2. Print the initial list using the print() function.
  3. Assign the value 4 to the variable rmv_element. This value represents the element that we want to remove from the list.
  4. Use the if statement to check if the rmv_element is present in the list test_list1.
  5. If the element is present, use the pop() method to remove the first occurrence of the element from the list. The index() method is used to find the index of the element to be removed.
  6. Print the list after removal using the print() function. 

Python3




# Python code to demonstrate
# element removal in list
# using pop() method
 
test_list1 = [1, 3, 4, 6, 3]
 
# Printing initial list
print("The list before element removal is : "
      + str(test_list1))
 
rmv_element = 4
 
# using pop()
# to remove list element 4
if rmv_element in test_list1:
    test_list1.pop(test_list1.index(rmv_element))
 
# Printing list after removal
print("The list after element removal is : "
      + str(test_list1))
 
# Added by Paras Jain(everythingispossible)


Output :

The list before element removal is : [1, 3, 4, 6, 3]
The list after element removal is : [1, 3, 6, 3]

Method #6: Using Recursion 

Using Recursion to remove an element in a list

Python3




def remove_element(start, oldlist, newlist, element):
    if start == len(oldlist):
        return newlist  # base condition
    if oldlist[start] == element:
        pass  # checking if element is oldlist pass
    else:
        newlist.append(oldlist[start])  # appending oldlist element to new list
    return remove_element(start+1, oldlist, newlist, element)
 
 
# Driver code
newlist = [1, 2, 3, 29, 2, 13, 421, 31]
start = 0
element = 2  # element want to remove
print('The list Before removal: ', newlist)
print('The list After removal: ', remove_element(start, newlist, [], element))


Output :

The list Before removal:  [1, 2, 3, 29, 2, 13, 421, 31]
The list After removal:  [1, 3, 29, 13, 421, 31]

The time complexity of the given remove_element function is O(n), where n is the length of the input list oldlist. 

The auxiliary space complexity of the function is also O(n), where n is the length of the input list oldlist.



Previous Article
Next Article

Similar Reads

Python | Remove particular element from tuple list
Since the advent of the popularity of Python in data analysis, we have a list of tuples as a container in many of our problems. Sometimes, while data preprocessing, we might have a problem in which we need to completely remove a particular element from a list of tuples. Let's discuss a way in which this task can be performed. Removing element for t
7 min read
Python - Remove dictionary from a list of dictionaries if a particular value is not present
Given a list of dictionaries, remove all dictionaries which don't have K as a value. Examples: Input : test_list = [{"Gfg" : 4, "is" : 8, "best" : 9}, {"Gfg" : 3, "is": 7, "best" : 5}], K = 7 Output : [{'Gfg': 4, 'is': 8, 'best': 9}] Explanation : Resultant dictionary doesn't contain 7 as any element.Input : test_list = [{"Gfg" : 4, "is" : 7, "best
5 min read
Python | Get elements till particular element in list
Sometimes, while working with Python list, we can have a requirement in which we need to remove all the elements after a particular element, or, get all elements before a particular element. These both are similar problems and having a solution to it is always helpful. Let's discuss certain ways in which this task can be performed. Method #1 : Usin
7 min read
Python | Group strings at particular element in list
Sometimes, while working with Python list, we can have a problem in which we have to group strings in a way that at occurrence of particular element, the string list is grouped. This can be a potential problem of day-day programming. Let's discuss certain way in which this problem can be performed. Method 1: Using groupby() + list comprehension + l
7 min read
Python - Remove particular data type Elements from Tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to remove particular data type elements from tuple. This kind of problem can occur in domains which require data preprocessing. Let's discuss certain ways in which this task can be performed. Input : test_tuple = (4, 5, 'Gfg', 7.7, 'Best'), data_type = str Output :
6 min read
Python | Split list into lists by particular value
In Python, To split a list into sublists based on a particular value. The idea is to iterate through the original list and group elements into sub-lists whenever the specified value is encountered. It is often necessary to manipulate and process lists, especially when dealing with large amounts of data. One frequent operation is dividing a list int
5 min read
Python | Get values of particular key in list of dictionaries
Sometimes, we may require a way in which we have to get all the values of the specific key from a list of dictionaries. This kind of problem has a lot of applications in the web development domain in which we sometimes have a JSON and require just to get a single column from records. Let's discuss certain ways in which this problem can be solved. M
10 min read
Group List of Dictionary Data by Particular Key in Python
Group List of Dictionary Data by Particular Key in Python can be done using itertools.groupby() method. Itertools.groupby() This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items. Syntax: itertools.groupby(iterable, key_func) Parameters: iterable: Iterable can be of any kind (list, tuple,
3 min read
Python - Check if list contain particular digits
Given a List and some digits, the task is to write a python program to check if the list contains only certain digits. Input : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5, 3] Output : True Explanation : All elements are made out of 1, 4, 5 or 3 only.Input : test_list = [435, 133, 113, 451, 134], digs = [1, 4, 5] Output : False Explanatio
14 min read
Get a list of a particular column values of a Pandas DataFrame
In this article, we'll see how to get all values of a column in a pandas dataframe in the form of a list. This can be very useful in many situations, suppose we have to get the marks of all the students in a particular subject, get the phone numbers of all the employees, etc. Let's see how we can achieve this with the help of some examples. Pandas
3 min read
Practice Tags :