How to find duplicates from a list in Python

What are duplicates in a list?

If an integer or string or any items in a list are repeated more than one time, they are duplicates.

Example

Consider a list with integers, list=[2,3,1,5,4,3,2,1].

In the list above, 2,3, and 1 are duplicates because the occurrence of these integers is more than one.

Code

The code below shows how to find a duplicate in a list in Python:

l=[1,2,3,4,5,2,3,4,7,9,5]
l1=[]
for i in l:
if i not in l1:
l1.append(i)
else:
print(i,end=' ')

Explanation

  1. The list (l) with duplicate elements is taken to find the duplicates.

  2. An empty list (l1) is taken to store the values of non-duplicate elements from the given list.

  3. The for loop is used to access the values in the list (l), and the if condition is used to check if the elements in the given list (l) are present in the empty list (l1).

  4. If the elements are not present, those values are appended to the list (l1); else, they are printed.

  5. Here, the list (l1) has no duplicates. The values printed are the duplicates from list (l).

Free Resources