Find Duplicate Values using Python

Finding duplicate values from an array or any other data structure is one of the popular coding interview questions that you can get in any coding interview. The Python programming language provides many inbuilt functions to find the duplicate values, but in a coding interview, you should use an algorithm instead of an inbuilt function. So if you want to learn how to find duplicate values, this article is for you. In this article, I will take you through how to write a program to find duplicate values using Python.

Find Duplicate Values using Python

To write a program to find duplicate values using Python, I will define a Python function that will take a list of values in any data type. So below is a Python function for finding duplicate values in a list:

def find_duplicates(x):
    length = len(x)
    duplicates = []
    for i in range(length):
        n = i + 1
        for a in range(n, length):
            if x[i] == x[a] and x[i] not in duplicates:
                duplicates.append(x[i])
    return duplicates
names = ["Aman", "Akanksha", "Divyansha", "Devyansh", 
         "Aman", "Diksha", "Akanksha"]
print(find_duplicates(names))
['Aman', 'Akanksha']

Below is how the above function works:

  1. The above function takes a list as an input;
  2. Then it calculates the length of the list;
  3. Then it looks for the same value in the list that is found on the first index;
  4. If it finds multiple values, it appends that value in another list of duplicate values;
  5. This process continues till the loop reaches the final index of the list. In the end, it returns the list of duplicate values. 

You can use this function on a Python list of any data type.

Summary

So this is how you can write a Python function for finding the duplicate values in a list of any data type. The Python programming language provides many inbuilt functions to find the duplicate items, but in a coding interview, you should use an algorithm instead of an inbuilt function. I hope you liked this article about finding duplicate values in a Python list. Feel free to ask valuable questions in the comments section below.

Default image
Aman Kharwal

Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder

Articles: 1211

One comment

  1. Thank you Aman Kharwal but i want to know how do use matching to search a value in a list or a dataframe.

    For example value is : “blue” but in the list it’s “blu” or “bluw”

Leave a Reply