How do I find the duplicates in a list and create another list with them?
In Python, one way to find duplicates in a list and create another list with them is to use a for loop and an if statement. Here is an example code snippet:
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 6, 8]
duplicate_list = []
for i in original_list:
if original_list.count(i) > 1:
if i not in duplicate_list:
duplicate_list.append(i)
print(duplicate_list)
This code first creates an empty list called "duplicate_list" to store the duplicates. Then, it iterates through the elements of the "original_list" using a for loop. For each element, it checks if the count of that element in the "original_list" is greater than 1 (i.e., if it is a duplicate). If it is, it then checks if the element is already in the "duplicate_list", and if not, it adds it to the "duplicate_list". Finally, it prints out the "duplicate_list".
Alternatively, you can use set to get unique element and then compare it with original list
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 4, 6, 8]
duplicate_list = [item for item in original_list if original_list.count(item) > 1]
print(duplicate_list)
This code snippet uses list comprehension and count function to get the duplicates from the original list.