Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of unique items in a list of tuples

I have a list of tuples like this: mylist = [(1,2,3),(6,1,1),(7,8,1),(3,4,5)]. If I use the list comprehension slist = [item for sublist in mylist for item in sublist], I could get slist = [1,2,3,6,1,1,7,8,1,3,4,5].

How should I modify if I need only unique elements in slist like this [1,2,3,6,7,8,4,5]?

like image 909
bdhar Avatar asked Dec 01 '22 01:12

bdhar


1 Answers

Use a set instead of a list.

set(slist)

If you really need it as a list then you can convert it back to a list:

slist = list(set(slist))

Note that this conversion won't preserve the original order of the elements. If you need the same order you can use this instead:

>>> result = []
>>> seen = set()
>>> for innerlist in mylist:
        for item in innerlist:
            if not item in seen:
                seen.add(item)
                result.append(item)
>>> result
[1, 2, 3, 6, 7, 8, 4, 5]
like image 188
Mark Byers Avatar answered Dec 04 '22 07:12

Mark Byers