Another approach: Using set intersection
Python3
def remove_common(a, b): common = set (a) & set (b) a = [i for i in a if i not in common] b = [i for i in b if i not in common] print ( "list1 : " , a) print ( "list2 : " , b) a = [ 1 , 2 , 3 , 4 , 5 ] b = [ 4 , 5 , 6 , 7 , 8 ] remove_common(a, b) |
list1 : [1, 2, 3] list2 : [6, 7, 8]
Time Complexity: O(nlogn), where n is the number of elements in the list. The set intersection operation takes O(nlogn) time.
Auxiliary Space: O(n), where n is the number of elements in the list. The set requires O(n) space to store the elements.
Explanation:
We convert both the lists into sets and use the set intersection operation to find the common elements.
Then we use list comprehension to remove the common elements from both the lists and return the updated lists.
Remove common elements from two list in Python
Given two lists, the task is to write a Python program to remove all the common elements of two lists.
Examples:
Input : list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8,]
Output : list1 = [1, 2, 3]
list2 = [6, 7, 8]
Explanation: Lists after removing common elements of both the lists i.e, 4 and 5.
Input : list1 = [1, 2, 3]
list2 = [1, 2, 3]
Output : list1 = []
list2 = []
Explanation: They have all the elements in common in
between them.