How to Return Duplicates in a Python List?

Estimated read time 2 min read

To return duplicates in a Python list, you can use a variety of approaches. Here are some options:

  1. Using a Set: You can use a set to remove duplicates from a list and then compare the length of the original list with the set. If the lengths are different, it means that there are duplicates in the original list. Here’s an example:
def get_duplicates(input_list):
    unique_set = set(input_list)
    if len(unique_set) == len(input_list):
        return None  # no duplicates found
    else:
        duplicates = []
        for item in unique_set:
            if input_list.count(item) > 1:
                duplicates.append(item)
        return duplicates

my_list = [1, 2, 3, 4, 5, 3, 4, 6, 7]
result = get_duplicates(my_list)
print(result)  # Output: [3, 4]

In this example, the get_duplicates() function takes a list as an input and first creates a set to remove duplicates. If the length of the set and the original list are the same, it means that there are no duplicates, and the function returns None. If the lengths are different, the function identifies the duplicates by iterating over the unique set and counting the occurrences of each item in the original list.

  1. Using a Dictionary: You can use a dictionary to keep track of the occurrences of each item in the list and then return the items that occur more than once. Here’s an example:
def get_duplicates(input_list):
    counter_dict = {}
    for item in input_list:
        if item in counter_dict:
            counter_dict[item] += 1
        else:
            counter_dict[item] = 1
    duplicates = [item for item, count in counter_dict.items() if count > 1]
    if len(duplicates) == 0:
        return None  # no duplicates found
    else:
        return duplicates

my_list = [1, 2, 3, 4, 5, 3, 4, 6, 7]
result = get_duplicates(my_list)
print(result)  # Output: [3, 4]

In this example, the get_duplicates() function uses a dictionary to count the occurrences of each item in the list. It then returns a list of items that occur more than once. If there are no duplicates, the function returns None.

Choose the approach that best fits your needs depending on the context and the specific requirements of your code.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply