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))
Below is how the above function works:
- The above function takes a list as an input;
- Then it calculates the length of the list;
- Then it looks for the same value in the list that is found on the first index;
- If it finds multiple values, it appends that value in another list of duplicate values;
- 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.
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.