Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Remove all values from a list present in other list

Python | Remove all values from a list present in other list

Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which need to be get ridden from the original list. Let’s discuss various ways How to remove the elements of a list from another list in Python.

Illustration:

Input:
List one is : [1, 3, 4, 6, 7]
List two is : [3, 6]
Output:
The list after performing the remove operation is : [1, 4, 7]

Method 1: Using list comprehension to remove all values from a list present in other list

The list comprehension can be used to perform the naive method in just one line and hence gives an easy method to perform this particular task.

Python3




# Python 3 code to demonstrate
# to remove elements present in other list
# using list comprehension
 
# Initializing list
test_list = [1, 3, 4, 6, 7]
 
# Initializing remove list
remove_list = [3, 6]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Printing remove list
print("The original list is : " + str(remove_list))
 
# Removing elements present in other list
# using list comprehension
res = [i for i in test_list if i not in remove_list]
 
# Printing the result
print("The list after performing remove operation is : " + str(res))


Output

The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : [1, 4, 7]

Time complexity: O(n^2), where n is the length of the test_list.
Auxiliary space: O(n), where n is the length of the test_list.

Method 2: Using filter() + lambda to remove all values from a list present in other list 

The filter function can be used along with lambda to perform this task and create a new filtered list of all the elements that are not present in the remove element list.

Python3




# Python 3 code to demonstrate
# to remove elements present in other list
# using filter() + lambda
 
# Initializing list
test_list = [1, 3, 4, 6, 7]
 
# Initializing remove list
remove_list = [3, 6]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Printing remove list
print("The original list is : " + str(remove_list))
 
# Removing elements present in other list
# Using filter() + lambda
res = filter(lambda i: i not in remove_list, test_list)
 
# Printing the result
print("The list after performing remove operation is : " + str(res))


Output

The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : <filter object at 0x7f28f3279f10>

Time complexity: O(n), where n is the length of the test_list. 
Auxiliary space: O(1). The code uses only a constant amount of extra memory, as no new lists or other data structures are created

Method 3: Using remove() to remove all values from a list present in other list

remove() can also perform this task but only if the exception of not getting specific elements is handled properly. One can iterate for all the elements of the removed list and remove those elements from the original list.

Example:

Python3




# Python 3 code to demonstrate
# to remove elements present in other list
# using remove()
 
# Initializing list
test_list = [1, 3, 4, 6, 7]
 
# Initializing remove list
remove_list = [3, 6]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Printing remove list
print("The original list is : " + str(remove_list))
 
# using remove() to perform task
# handled exceptions
for i in remove_list:
    try:
        test_list.remove(i)
    except ValueError:
        pass
 
# Printing the test list as result
print("The list after performing remove operation is : " + str(test_list))


Output

The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : [1, 4, 7]

Output: 

The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : [1, 4, 7]

Time complexity: O(n*m), where n is the length of test_list and m is the length of remove_list.
Auxiliary space: O(1), as the only additional memory used, is for the two lists test_list and remove_list, and no additional data structures or variables are used within the loop.

Method 4: Using set() to remove all values from a list present in other lists

set() can be used to perform this task and create a new filtered list of all the elements that are not present in the remove element list.

Python3




# Python 3 code to demonstrate
# to remove elements present in other list
# using set()
 
# Initializing list
test_list = [1, 3, 4, 6, 7]
 
# Initializing remove list
remove_list = [3, 6]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Printing remove list
print("The original list is : " + str(remove_list))
 
# Removing elements present in other list
# using set() to perform task
set1 = set(test_list)
set2 = set(remove_list)
res = list(set1 - set2)
 
# Printing the result
print("The list after performing remove operation is : " + str(res))


Output

The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : [1, 4, 7]

Method 5: Using the itertools module to remove all values from a list present in other list

Here we are using the itertools module to remove the elements of a list from another list in Python.

Python3




from itertools import filterfalse
 
# Input test list and list to be removed
test_list = [1, 3, 4, 6, 7]
remove_list = [3, 6]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Printing remove list
print("The original list is : " + str(remove_list))
 
res = list(filterfalse(remove_list.__contains__,
                       test_list))
 
# Printing the resultant list after removal
print("The list after performing remove operation is : " + str(res))


Output

The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : [1, 4, 7]

Method 6: Using set difference

One way to remove all values from a list present in another list is to use a combination of sets and list comprehension. First, you can convert both lists to sets and then use the difference method to find the elements in the first list that are not present in the second list. Finally, you can use list comprehension to convert the resulting set back to a list.

Python3




# initializing lists
original_list = [1, 3, 4, 6, 7]
remove_list = [3, 6]
 
# Removing values from original_list that are present
# in remove_list using difference()
filtered_list = list(set(original_list).difference(remove_list))
 
# Printing result
print(filtered_list) 
 
# This code is contributed by Edula Vinay Kumar Reddy


Output

[1, 4, 7]

Time Complexity: O(N)
Auxiliary Space: O(N), where n is the length of the longer list. It is a relatively efficient way to remove all values from a list present in another list.

Method 7: Using slicing

Python3




# Initializing lists
 
# Defining the original list of values
test_list = [1, 3, 4, 6, 7]
# Defining a list of values to remove from the original list
remove_list = [3, 6]
 
# Creating a new list with all values from the original list
# that are not in the remove list
res = [x for x in test_list if x not in remove_list]
 
# Updating the original list to be the new list of values
test_list[:] = res
 
# Printing the updated original list
print(test_list)


Output

[1, 4, 7]

Approach:

  1. Define the original list of values.
  2. Define a list of values to remove from the original list.
  3. Use list comprehension to create a new list with all values from the original list that are not in the remove list.
  4. Update the original list to be the new list of values using slice assignment.
  5. Print the updated original list.

Time complexity: O(n^2), where n is the length of the original list, because, for each element in the original list, we check if it is in the remove list using the in operator, which has a time complexity of O(n). The overall time complexity is therefore O(n^2). 
Auxiliary space: O(n), because we create a new list to store the values that are not in the remove list.

Method 8: Using Recursive method

Algorithm:

  1. Define a recursive function called “remove_values_recursive” that takes two arguments: “original_list” and “remove_list”.
  2. Check if the length of the original_list is 0. If it is, return an empty list.
  3. If the length of the original_list is not 0, check if the first element of the original_list is in the remove_list.
  4. If it is, call the remove_values_recursive function again with the rest of the original_list (i.e. without the first element).
  5. If it’s not, add that element to a new list and call the remove_values_recursive function again with the rest of the original_list.
  6. Repeat steps 3 to 5 until the original_list is empty.
  7. Concatenate all the lists obtained from recursive calls in step 5 and return the final result.

Python3




def remove_values_recursive(original_list, remove_list):
    if len(original_list) == 0:
        return []
    else:
        if original_list[0] in remove_list:
            return remove_values_recursive(original_list[1:], remove_list)
        else:
            return [original_list[0]] + remove_values_recursive(original_list[1:], remove_list)
 
# define the original list of values
test_list = [1, 3, 4, 6, 7]
 
# define a list of values to remove from the original list
remove_list = [3, 6]
 
# create a new list with all values from the original list that are not in the remove list
res = remove_values_recursive(test_list, remove_list)
 
 
 
# print the updated original list
print(res)


Output

[1, 4, 7]

Time complexity: O(N), where n is the length of the original list. This is because we are iterating through each element of the original list exactly once.

Auxiliary space: O(N), since each recursive call creates a new list containing one element from the original list, and each of those lists are stored in memory until the base case is reached. Therefore, if the original list is very large, this method may not be the most memory-efficient.

Method 9: Using numpy.setdiff1d()

This approach makes use of the numpy library’s setdiff1d() function, which returns the elements that are in the first array and not in the second array. We first convert the input lists to numpy arrays, then use setdiff1d() to get the elements we want to keep in the resulting list. We then convert this resulting numpy array back to a list using the tolist() method.

Algorithm:

  1. Convert the input lists to numpy arrays.
  2. Use setdiff1d() function to get the elements that are in the first array and not in the second array.
  3. Convert the resulting numpy array back to a list using the tolist() method.
  4. Print the original lists.
  5. Print the resulting list after performing the remove operation.

Python3




# Python 3 code to demonstrate
# to remove elements present in other list
# using numpy.setdiff1d()
 
import numpy as np
 
# Initializing list
test_list = [1, 3, 4, 6, 7]
 
# Initializing remove list
remove_list = [3, 6]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Printing remove list
print("The original list is : " + str(remove_list))
 
# Removing elements present in other list
# using numpy.setdiff1d() function
res = np.setdiff1d(test_list, remove_list).tolist()
 
# Printing the resultant list
print("The list after performing remove operation is : " + str(res))


Output:

The original list is : [1, 3, 4, 6, 7]
The original list is : [3, 6]
The list after performing remove operation is : [1, 4, 7]

Time complexity: O(n*log(n)), where n is the length of the test_list.
Auxiliary Space: O(n), where n is the length of the test_list.

Previous article
Next article
RELATED ARTICLES

Most Popular

Recent Comments