Python Program to print duplicates from a list of integers



Python | Program to print duplicates from a list of integers

Given a list of integers with duplicate elements in it. The task to generate another list, which contains only the duplicate elements. In simple words, the new list should contain the elements which appear more than one.
Examples :

Input : list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]
Output : output_list = [20, 30, -20, 60]


Input :  list = [-1, 1, -1, 8]
Output : output_list = [-1]

Method 1: Using the Brute Force approach

Below is the implementation :

# Python program to print
# duplicates from a list
# of integers
def Repeat(x):
    _size = len(x)
    repeated = []
    for i in range(_size):
        k = i + 1
        for j in range(k, _size):
            if x[i] == x[j] and x[i] not in repeated:
                repeated.append(x[i])
    return repeated
# Driver Code
list1 = [10, 20, 30, 20, 20, 30, 40,
         50, -20, 60, 60, -20, -20]
print (Repeat(list1))
    
# This code is contributed
# by Sandeep_anand

Output :

[20, 30, -20, 60]

Method 2: Using Counter() function from collection module

from collections import Counter
l1 = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]
d = Counter(l1)
print(d)
new_list = list([item for item in d if d[item]>1])
print(new_list)

Output

Counter({1: 4, 2: 3, 5: 2, 9: 2, 3: 1, 4: 1, 6: 1, 7: 1, 8: 1})
[1, 2, 5, 9]

 

Last Updated on October 29, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs