Javaexercise.com

Python Program To Find Duplicate Elements in a List

To find duplicate elements in the Python list, we created a program that traverse the list elements and list out the duplicate elements. Elements that appear more than once in the list are called duplicate elements.

In this post, we have certain examples in which we print duplicate elements to the console and in another example we created a list of duplicate elements.

Program To Print Duplicate Elements

Lets take an example to print duplicate elements of a list. This example uses sequential approac to find and print duplicate elements.

# Take a list
list = [2,3,6,8,11,2,5,6,8,4,3]
# Traverse the list elements
for element in range(0, len(list)):
	for nextElement in range(element+1,len(list))
		# Check duplicate elements
		if list[element] == list[nextElement]:
			# Print duplicate elements
			print(list[element])

 

Output:

2
3
6
8
 

Program To Get List of Duplicate Elements

Sometimes we need to store duplicate elements for further processing in the application. In that case, we can store these duplicate elements into a list by using list append() method. See the example, where we have two lists: one that contains elements and second to store the duplicate elements.

# Take a list
list = [2,3,6,8,11,2,5,6,8,4,3]
# Take an empty list to store duplicate elements
newList = [];
# Traverse the list elements
for element in range(0, len(list)):
	for nextElement in range(element+1,len(list)):
		# Check duplicate elements
		if list[element] == list[nextElement]:
			# Add duplicate elements
			newList.append(list[element])
# Print list of duplicate elements
print(newList)

 

Output:

[2, 3, 6, 8]
 

Program To Get List of Non Duplicate Elements

In the above program, we got list of duplicate elements. Now, here we are getting list of unique elements after removing duplicate elements. In the below example, we created a new list to store unique elements by using append() method of Python list. 

# Take a list
list = [2,3,6,8,11,2,5,6,8,4,3]
# Take an empty list to store non duplicate (unique) elements
newList = [];
# Traverse the list elements
for element in list:
		# Check for the element
		if element not in newList:
			# Add element
			newList.append(element)
# Print list of unique elements
print(newList)

 

Output:

[2, 3, 6, 8, 11, 5, 4]
 


Conclusion

Well, in this topic, we learnt to write a program to check whether a python list contains duplicate elements or not. We get list of duplicate elements and in another program we removed all the duplicate elements.