0

I have the following python list :-

a=[['t1', ['a', 'c']], ['t2', ['b']], ['t2', ['b']]]

now it contains duplicate lists within it ['t2', ['b']] 2 times I want to return true if the list contains duplicates. Can anyone please help me how to do so ?

I tried to use the set function but it is not working here !

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Kanika Singh
  • 77
  • 1
  • 2
  • 6

2 Answers2

0

If your aim is to remove duplicates, this answer might be helpful:

unique_a = [i for n, i in enumerate(a) if i not in a[:n]]

You can rewrite it this way:

has_duplicates = lambda l: True in [(i in l[:n]) for n, i in enumerate(l)]

You can call it this way:

has_duplicates(a)   # True
Community
  • 1
  • 1
Mehdi
  • 4,202
  • 5
  • 20
  • 36
0

If you are free to represent your list a as a list of tuples/records:

b = [(item[0], tuple(item[1])) for item in a]

(or, in the first place):

a = [('t1', ('a', 'c')), ('t2', ('b')), ('t2', ('b'))]

Then the items become hashable and you can use collections.Counter:

from collections import Counter
c = Counter(b)

So you can find duplicates like:

duplicated_items = [key for key, count in c.iteritems() if count > 1]

(Or you can use set):

has_duplicates = len(set(b)) < len(b)
Leo
  • 1,077
  • 11
  • 24