Find Duplicates in List Python: Quick Guide
You can use the set() function and list comprehension in Python to find duplicate values in a list. Here are the specific steps:
- Create an empty set called “duplicates” to store duplicate values.
- Traverse each element in the list using list comprehension.
- If the element already exists in the collection, it will be added to the duplicate list.
- Otherwise, add the element to the collection.
- Finally, return to the duplicate list.
Here is an example code snippet:
def find_duplicates(lst):
duplicates = []
seen = set()
for item in lst:
if item in seen:
duplicates.append(item)
else:
seen.add(item)
return duplicates
# 示例用法
my_lst = [1, 2, 3, 4, 3, 2, 1, 5]
result = find_duplicates(my_lst)
print(result) # 输出 [1, 2, 3]
In this example, the input list my_lst contains duplicate values of 1, 2, and 3. The code will identify these duplicates and store them in a list called result, then print them out in the end.