Remove The Elements Of A List From Another List In Python

The list is a data structure used in programming. It helps us handle different elements and there are many ways to handle them. Using Python programming it’s quite easy to remove a specific element from another list in Python. However, Removing the elements of a list from another list is not a trivial task. In Python, you can remove elements from another list using the built-in functions. This page will show you an efficient solution to this problem by making use of Python’s built-in functions.

*Working on Jupyter Notebook → Anaconda Navigator

Let’s dive into the article details:

Using list comprehension removes elements from another list

The list comprehension has a structure of for…in. In a single line using for…in structure, the command lines execution is possible. 

Here is an example below, list comprehension is executed in a single line. Each element is read from the index, and the list is filled with all of those elements. 

The execution process executes in the following sequence:

  • Creating a two list
  • In a square bracket, execute the list comprehension command line. Here in this line, we want to remove elements from the second list common with reference to the first list. 
  • Here for..in structure performing a task in execution with remove function
  • Then print the required list in a print () function, by passing the required list in the print function. 
Source Code:
list_1 = ['coding', 'is','fun']
list_2 = ['fun']
[list_1.remove(item) for item in list_2 if item in list_1]
print(type(list_1))
list_1

<class 'list'>
['coding', 'is']

List comprehension without removing the method

List comprehension performing a task without removing function. 

  • Forming a two lists
  • In a square bracket execution the for..in structure, to remove the elements of a list from the other list. 
  • The execution line in the example source code, removes the elements from the list_2 that is present or common in list_1. 
lst1, lst2 = ['coding', 'is','fun'], ['is', '1','2']
lst3 = [x for x in lst1 if x not in lst2]
print(type(lst3))
lst3
<class 'list'>
['coding', 'fun']

Using non-list comprehension in aggregation with the continue statement 

The continue statement is used for the current iteration only in Python, the continue statement skips the rest of a loop’s code. There is no termination of the loop, but instead, the loop continues to iterate.

Here non-list comprehension method is used in aggregation with a continue statement to remove the elements of a list from another list in Python. 

The execution process executes in the following sequence:

  • Creating a two lists
  • Now create a new empty list.
  • For the non-list comprehension, the iterator returns the new_list, which contains the list of new elements. 
  • If continue is not added, it will return an error, so iterate the loop, continue statement is injected in code. 
list_1 = ['my',"name", "is", "x"]
list_2 = ['my',"name"]
new_list=[]
for x in list_1:
   if x in list_2:
       continue
   new_list=new_list+[x]
print(type(new_list))
new_list
<class 'list'>
['is', 'x']

Using lambda expression to remove items of a list from another list in Python

Lambda expression allows us to remove elements of a list from another list in Python. Lambda expressions can return only a single expression, after computing operations on an argument. Here in the following example, 

  • After computing the logical operation, the lambda() function in aggregation with the filter() function returns a single expression.
  • Lambda evaluates its arguments and searches and matches the elements that are not present in the list to be removed but contained in the original list.
  • A filter() function returns an iterator that includes those elements in an iterable that matches lambda function(element). It removes those elements from lambda results that are not in the removing list from another list.
remove_element_from_list = ["toppers",['a','c',3],"runner_ups",1,2]
remove_element_from_list_2 = ["runner_ups",1,2]
list(filter(lambda x: x not in remove_element_from_list_2, remove_element_from_list))
['toppers', ['a', 'c', 3]]

Using filterfalse() to remove elements of a list from another list in Python

Importing filterfalse from itertools provides flexibility  to remove elements of a list that are present in another list in  Python. 

However, using filterfalse() in aggregation with __contains__ method using the (.) operator makes the task more straightforward. Here is how it executes in the following example:

from itertools import filterfalse
remove_element_from_list = ["toppers",['a','c',3],"runner_ups",1,2]
remove_element_from_list_2 = ["runner_ups",1,2]
#using filterfalse to remove element from one list to another list
list(filterfalse(remove_element_from_list_2.__contains__, remove_element_from_list))
['toppers', ['a', 'c', 3]]

Using list comprehension structure to remove elements of a list from another list in Python

The for…in structure of list comprehension allows us to remove elements of a list that are present in another list. 

Remember, when handling list comprehension enclosed the one-liner program within square brackets, to give justice with Pythonic syntax structure, 

remove_element_from_list = ["toppers",['a','c',3],"runner_ups",1,2]
remove_element_from_list_2 = ["runner_ups",1,2]
#using list comprehension to remove element from one list to another list
[i for i in remove_element_from_list if i not in remove_element_from_list_2]
['toppers', ['a', 'c', 3]]

Using difference(-) to remove all values from a list present in another list

The set() function can be used to filter the removed element list and create a new filtered list of all the elements that are not present in the other list.

Here in the following example:

  • Convert the list to set(), containing lists
  • Then using a difference operator to remove the elements of a list from another list in Python. 
  • Convert the difference to a list again using built-in list method.

[0] is appended to the output to remove square brackets and commas, [‘’].

remove_element_from_list = ["toppers","runner_ups",1,2]
remove_element_from_list_2 = ["runner_ups",1,2]
set_1=set(remove_element_from_list)
set_2=set(remove_element_from_list_2)
# using set() with difference operator
difference = list(set_1 - set_2)
#[0] append to remove square brackets and commas from the results
print ("remove element from in a list to another list is : ", (difference)[0])
remove element from in a list to another list is :  toppers

Using set().difference()  to remove the elements of a list from another list in  Python

Using set().difference() expression to remove the elements of a list from another list in Python. Here is how it executes: 

remove_element_from_list = ["toppers","runner_ups",1,2]
remove_element_from_list_2 = ["runner_ups",1,2]
# using difference() function to remove elements in a list that are present in other list
removed_element_list = list(set(remove_element_from_list).difference(remove_element_from_list_2))
print ("remove element from in a list to another list is : ", removed_element_list[0], type(removed_element_list))
remove element from in a list to another list is :  toppers <class 'list'>

Using remove() to remove the elements of a list from another list in Python

The remove() function is the first and straightforward approach when there is a need to remove the elements of a list from another list in Python. 

Using for…in structure to iterate remove_element_from_list_2 over remove_element_from_list, and remove function search and remove those elements of a list that are not present in another list in Python.  Here’s how it executes:

remove_element_from_list = ["toppers",['a','c',3],"runner_ups",1,2]
remove_element_from_list_2 = ["runner_ups",1,2]
# using remove()
for i in remove_element_from_list_2:
       remove_element_from_list.remove(i)
print ("The list after performing remove operation is : " + str(remove_element_from_list))
The list after performing remove operation is : ['toppers', ['a', 'c', 3]]

Using the remove() function to remove an element from a nested list

def nested_list_remove(remove_element_from_list, i):
   if i in remove_element_from_list:
       remove_element_from_list.remove(i)
   else:
       for element in remove_element_from_list:
           if type(element) is list:
               nested_list_remove(element, i)
              
              
remove_element_from_list = ["toppers",['a','c',3],"runner_ups",['d','e','f']]
nested_list_remove(remove_element_from_list, ['d','e','f'])
remove_element_from_list
['toppers', ['a', 'c', 3], 'runner_ups']

Using pop() to remove the elements of a list from another list in Python

You can remove an item from a list by calling the pop() method with the element’s index. By default, If no index value is passed, the pop() returns the last element of the list and removes it. 

Here in the following example, pop() function removes the remove_element_from_list_2 from remove_element_from_list during iteration of for..in structure over remove_element_from_list_2. 

remove_element_from_list = ["toppers","runner_ups",1,2]
remove_element_from_list_2 = [1,2]
# using pop()
for i in remove_element_from_list_2:
       remove_element_from_list.pop()
print ("The list after performing remove operation is : ",list(remove_element_from_list))
The list after performing remove operation is :  ['toppers', 'runner_ups']

Using pop() function to remove items from the nested lists

In this example, you will learn how to use pop() to remove items from a list.

The execution process goes in the following manner:

  • The task of removing an item of a list is accomplished using while and break iterations. 
  • The argument passed in the pop() is 0, which means that iteration starts from the index location 0.
  • And if the condition specifies that during execution if there are ‘c’ matches, the break command will terminate the process there.
  • However, the output reads from the index location 0 and reads till the break calls at ‘c’. 
remove_element_from_list = ["toppers",['a','c',3],"runner_ups",1,2]
while remove_element_from_list:
   terminate_at=remove_element_from_list.pop(0)
   if terminate_at==['a','c',3]:
       break
   print(terminate_at)
toppers

Using the del operator to remove elements in a list present in a nested list. 

The del operator removes elements in a list present in a nested list. Here’s how it executes:

remove_element_from_list = ["toppers",['a','c',3],"runner_ups",1,2]
#del operator to remove items from list
del remove_element_from_list[1]
remove_element_from_list
['toppers', 'runner_ups', 1, 2]

Conclusion

Here on this page, different ways are mentioned using list comprehension methods and using other built-in functions and methods to remove elements of a list from another list in Python using examples. However, in this tutorial, different ways of removing elements of a list from another list in Python are demonstrated with examples, use the one that best fits your problems. 

If you want to learn more about Python Programming, visit Python Programming Tutorials.

Leave a Comment

Your email address will not be published. Required fields are marked *