1

Is there any inbuilt way to print duplicate elements present in a python list.

I can write program for the same.

All I'm searching for is if there is any inbuilt method or something for the same.

For Ex:

For input [4,3,2,4,5,6,4,7,6,8]

I need op 4,6

Leviand
  • 2,745
  • 4
  • 29
  • 43
Narendra
  • 13
  • 1
  • 1
  • 3
  • 1
    No. There is no built-in function for that – DeepSpace Aug 29 '18 at 07:59
  • 3
    You can use a list comprehension `print([i for i in set(a) if a.count(i) > 1])` – Rakesh Aug 29 '18 at 08:02
  • There's a numpy function to find unique elements, which can be used for this purpose. See https://stackoverflow.com/questions/25264798/checking-for-and-indexing-non-unique-duplicate-values-in-a-numpy-array – Denis Aug 29 '18 at 08:04

4 Answers4

6

There is the Counter class from collections that does the trick

from collections import Counter


lst = [4,3,2,4,5,6,4,7,6,8]
d =  Counter(lst)  # -> Counter({4: 3, 6: 2, 3: 1, 2: 1, 5: 1, 7: 1, 8: 1})
res = [k for k, v in d.items() if v > 1]
print(res)
# [4, 6]
Ma0
  • 15,057
  • 4
  • 35
  • 65
2

Possibly related duplicate question: How do I find the duplicates in a list and create another list with them?

Simple Answer:

>>> l = [1,2,3,4,4,5,5,6,1]
>>> set([x for x in l if l.count(x) > 1])
set([1, 4, 5])
sobczak.dev
  • 973
  • 7
  • 11
1

with simple built-in function you can do :

>>> a=[4,3,2,4,5,6,4,7,6,8]
>>> b=[a[i] for i in range(len(a)) if a[i] in a[:i]][1:]
>>> b
[4, 6]
Dadep
  • 2,796
  • 5
  • 27
  • 40
0

Here is a simple demo

    x = [1,2,3,5,3,2]
    y = []
    for a in x:
        if not a in y:
            y.append(a)
    print(a)

So here is how it works.Iterate over every items in x.If the current iteration item doesn't exist in y append it

Manos Kounelakis
  • 2,848
  • 5
  • 31
  • 55