When it is required to remove duplicate elements index from other list, the ‘enumerate’ attribute, the list comprehension and a simple iteration are used.
Example
Below is a demonstration of the same
my_list_1 = [4, 5, 6, 5, 4, 7, 8, 6] my_list_2 = [1, 7, 6, 4, 7, 9, 10, 11] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) temp_set = set() temp = [] for index, value in enumerate(my_list_1): if value not in temp_set: temp_set.add(value) else: temp.append(index) my_result = [element for index, element in enumerate(my_list_2) if index not in temp] print("The result is :") print(my_result)
Output
The first list is : [4, 5, 6, 5, 4, 7, 8, 6] The second list is : [1, 7, 6, 4, 7, 9, 10, 11] The result is : [1, 7, 6, 9, 10]
Explanation
- Two lists of integers is defined and is displayed on the console.
- An empty set is created and defined as ‘temp_set’.
- An empty list is created and defined as ‘temp’.
- The first list is iterated over using ‘enumerate’ attribute, and the elements of the first list are compared with the elements of the second list.
- If they match, the element is stored in a list.
- A list comprehension is used to iterate over the elements of second list and check if enumeration of elements of second list are present in the newly created list.
- It is converted to a list.
- This is assigned to a variable.
- This is displayed as output on the console.