user3448578
user3448578

Reputation: 39

Python - How to remove duplicate tuples in a list of lists?

I am having trouble removing tuples in the lists within a list.Basically I have this:

a = [[(4, 7), (4, 5)], [], [], [], [], [(4, 1)], [(4, 5), (4, 3)], [], [], [], [], [(4, 3), (4, 1)]]

i want every tuple only once.I also would like to remove the empty lists,something like that:

b = [[(4, 7)],[(4, 1)],[(4, 5)],[(4, 3)]]

the order doesn't matter but it's not just for this particular list(i want the code to work with any list made of lists with many tuples in them like this one). I tried set() but i can't figure out how it works.

Upvotes: 1

Views: 245

Answers (3)

kojiro
kojiro

Reputation: 77107

Itertools to the rescue:

from itertools import chain
list(set(chain.from_iterable(a)))
[(4, 5), (4, 7), (4, 1), (4, 3)]

If the nesting is really important:

[[t] for t in set(chain(*a))]

Upvotes: 4

Riccardo Galli
Riccardo Galli

Reputation: 12925

from itertools import chain
[[x] for x in set(chain(*a))]

Upvotes: 1

Mike Bell
Mike Bell

Reputation: 1386

I think you want something like this:

inp = [[(4, 7), (4, 5)], [], [], [], [], [(4, 1)], [(4, 5), (4, 3)], [], [], [], [], [(4, 3), (4, 1)]]

out = []
for lst in inp:
    for tup in lst:
        if [tup] not in out: 
            out.append([tup])
print out

[[(4, 7)], [(4, 5)], [(4, 1)], [(4, 3)]]

Upvotes: 0

Related Questions