Open In App

Python | Program to print duplicates from a list of integers

Last Updated : 29 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list of integers with duplicate elements in it. The task is to generate another list, which contains only the duplicate elements. In simple words, the new list should contain elements that appear as 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

Python3




# 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]

Time complexity: O(n^2) where n is the length of the input list
Auxiliary space: O(k) where k is the number of duplicates in the input list.

Method 2: Using a single for loop

Python3




# Python program to print duplicates from
# a list of integers
lis = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]
 
uniqueList = []
duplicateList = []
 
for i in lis:
    if i not in uniqueList:
        uniqueList.append(i)
    elif i not in duplicateList:
        duplicateList.append(i)
 
print(duplicateList)


Output

[1, 2, 5, 9]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 3: Using Counter() function from collection module

Python3




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]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using count() method

Python3




# program to print duplicate numbers in a given list
# provided input
list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]
 
new = []  # defining output list
 
# condition for reviewing every
# element of given input list
for a in list:
 
     # checking the occurrence of elements
    n = list.count(a)
 
    # if the occurrence is more than
    # one we add it to the output list
    if n > 1:
 
        if new.count(a) == 0# condition to check
 
            new.append(a)
 
print(new)
 
# This code is contributed by Himanshu Khune


Output

[1, 2, 5, 9]

Method 5: Using list comprehension method

Python3




def duplicate(input_list):
    return list(set([x for x in input_list if input_list.count(x) > 1]))
 
if __name__ == '__main__':
    input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]
    print(duplicate(input_list))
 
# This code is contributed by saikot


Output

[1, 2, 5, 9]

Method 6: Using list-dictionary approach (without any inbuild count function)

Python3




def duplicate(input_list):
    new_dict, new_list = {}, []
 
    for i in input_list:
        if not i in new_dict:
            new_dict[i] = 1
        else:
            new_dict[i] += 1
 
    for key, values in new_dict.items():
        if values > 1:
            new_list.append(key)
 
    return new_list
 
if __name__ == '__main__':
    input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]
    print(duplicate(input_list))
 
# This code is contributed by saikot


Output

[1, 2, 5, 9]

Method 7: Using in, not in operators and count() method

Python3




lis = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]
x = []
y = []
for i in lis:
    if i not in x:
        x.append(i)
for i in x:
    if lis.count(i) > 1:
        y.append(i)
print(y)


Output

[1, 2, 5, 9]

Method 8: Using enumerate function

Python3




input_list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]
print(list(set([x for i,x in enumerate(input_list) if input_list.count(x) > 1])))


Output

[1, 2, 5, 9]

Time Complexity: O(n)

Auxiliary Space: O(1)

Method 9: Using operator.countOf() method

Python3




import operator as op
# program to print duplicate numbers in a given list
# provided input
list = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]
 
new = []  # defining output list
 
# condition for reviewing every
# element of given input list
for a in list:
 
     # checking the occurrence of elements
    n = op.countOf(list, a)
 
    # if the occurrence is more than
    # one we add it to the output list
    if n > 1:
 
        if op.countOf(new, a) == 0# condition to check
 
            new.append(a)
 
print(new)
 
# This code is contributed by vikkycirus


Output

[1, 2, 5, 9]

Time Complexity: O(n)
Auxiliary Space: O(1)

Method 10 : Using operator.countOf(),in and not in operators

Python3




lis = [1, 2, 1, 2, 3, 4, 5, 1, 1, 2, 5, 6, 7, 8, 9, 9]
x = []
y = []
import operator
for i in lis:
    if i not in x:
        x.append(i)
for i in x:
    if operator.countOf(lis,i) > 1:
        y.append(i)
print(y)


Output

[1, 2, 5, 9]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 11 : Using numpy:

Algorithm:

  1. Initialize the list l1 with some values.
  2. Import the numpy library.
  3. Use numpy.unique() to get the unique values and their counts in the list l1.
  4. Use numpy.where() to get the indices of the elements in the counts array that are greater than 1.
  5. Use these indices to get the corresponding elements from the unique array.

Python3




import numpy as np
 
l1 = [1,2,1,2,3,4,5,1,1,2,5,6,7,8,9,9]
 
unique, counts = np.unique(l1, return_counts=True)
new_list = unique[np.where(counts > 1)]
 
print(new_list)
#This code is contributed by Rayudu


Output:
[1 2 5 9]

Time Complexity:

numpy.unique() has a time complexity of O(nlogn) due to the sorting step, where n is the length of the input array.
numpy.where() has a time complexity of O(n), where n is the length of the input array.
Indexing an array takes constant time O(1).
Therefore, the time complexity of this numpy code is O(nlogn), dominated by numpy.unique().

Auxiliary Space:

The space complexity of this numpy code is O(n), since we are storing the input list l1 and the output list new_list.
numpy.unique() and numpy.where() internally create intermediate arrays, but they are not included in the space complexity of this code because they are temporary and not stored in memory.



Similar Reads

Python - Ways to print longest consecutive list without considering duplicates element
Given, a list of Numbers, the task is to print the longest consecutive (Strictly) list, without considering duplicate elements. If there is more than one answer, print anyone. These type of problem are quite common while working on some web development projects in Django or flask. Below are some ways to solve the above task. Note : If there are mul
4 min read
Python | Merging duplicates to list of list
Sometimes, we need to perform the conventional task of grouping some like elements into a separate list and thus forming a list of lists. This can also help in counting and also get the sorted order of elements. Let's discuss certain ways in which this can be done. Method #1: Using collections.Counter() This particular function can prove to be quit
6 min read
Program to print N minimum elements from list of integers
Given a list of integers, the task is to generate another list with N minimum elements. Examples: Input: {23, 1, 6, 2, 90}Output: {1, 2}Input: {34, 21, 56, 42, 89, 90, -1}Output: {-1, 21}Approach: The idea is to use the concept used in Find the smallest and second smallest elements in an array. First, find the smallest number in the given list.Then
12 min read
Python | Program to count duplicates in a list of tuples
Given a list of tuples, write a Python program to check if an element of the list has duplicates. If duplicates exist, print the number of occurrences of each duplicate tuple, otherwise print "No Duplicates". Examples: Input : [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] Output : ('a', 'e') - 2 ('b', 'x') - 3 Input : [(0, 5), (6, 9)
6 min read
Python Program For Removing Duplicates From A Sorted Linked List
Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60. Recommended: Please solve it on "PRACTICE"
7 min read
Python Program For Removing Duplicates From An Unsorted Linked List
Write a removeDuplicates() function that takes a list and deletes any duplicate nodes from the list. The list is not sorted. For example if the linked list is 12->11->12->21->41->43->21 then removeDuplicates() should convert the list to 12->11->21->41->43. Recommended: Please solve it on "PRACTICE" first, before moving
4 min read
Python Program to Print all Integers that Aren't Divisible by Either 2 or 3
We can input a set of integer, and check which integers in this range, beginning with 1 are not divisible by 2 or 3, by checking the remainder of the integer with 2 and 3. Example: Input: 10 Output: Numbers not divisible by 2 and 3 1 5 7 Method 1: We check if the number is not divisible by 2 and 3 using the and clause, then outputs the number. C/C+
7 min read
Python Remove Duplicates from a List
The job is simple. We need to take a list, with duplicate elements in it and generate another list that only contains the element without the duplicates in them. Examples: Input : [2, 4, 10, 20, 5, 2, 20, 4] Output : [2, 4, 10, 20, 5] Input : [28, 42, 28, 16, 90, 42, 42, 28] Output : [28, 42, 16, 90] We can use not in on list to find out the duplic
3 min read
Python | Remove consecutive duplicates from list
In Python, we generally wish to remove the duplicate elements, but sometimes for several specific usecases, we require to have remove just the elements repeated in succession. This is a quite easy task and having a shorthand for it can be useful. Let's discuss certain ways in which this task can be performed. Method #1 : Using groupby() + list comp
4 min read
Python | Remove all duplicates and permutations in nested list
Given a nested list, the task is to remove all duplicates and permutations in that nested list. Input: [[-11, 0, 11], [-11, 11, 0], [-11, 0, 11], [-11, 2, -11], [-11, 2, -11], [-11, -11, 2]] Output: {(-11, 0, 11), (-11, -11, 2)} Input: [[-1, 5, 3], [3, 5, 0], [-1, 5, 3], [1, 3, 5], [-1, 3, 5], [5, -1, 3]] Output: {(1, 3, 5), (0, 3, 5), (-1, 3, 5)}
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg