Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a list of tuples and remove the duplicates?

Tags:

python

I'm trying to remove the duplicates out of tuples in a list and add them in a new list with out duplicates,

I tried to make two loops but and check for duplicates or sets but the problem there's three tuples

can anyone help me, I'm stuck here

example

[(2, 5), (3, 5), (2, 5)]

Output

[2, 3, 5]
like image 292
Joe Avatar asked Apr 04 '16 19:04

Joe


People also ask

How do I remove duplicates from a list of tuples?

To remove duplicate tuples from a list of tuples: Use the set() class to convert the list to a set of tuples. Any duplicate tuples will automatically get removed after the conversion. Use the list() class to convert the set back to a list.

How do you flatten a tuple list?

One method to flatten tuples of a list is by using the sum() method with empty lust which will return all elements of the tuple as individual values in the list. Then we will convert it into a tuple. Method 2: Another method is using a method from Python's itertools library.

How do I remove all duplicates from a list?

To remove the duplicates from a list, you can make use of the built-in function set(). The specialty of the set() method is that it returns distinct elements.

Does converting list to set remove duplicates?

Sets are data structures that cannot contain any duplicate elements. When you convert a list into a set, all the duplicates will be removed.


1 Answers

If order isn't important, you can make a set, add each element of each tuple to the set, and the set is your result.

s = set()
for tup in lst:
    for el in tup:
        s.add(el)
# or use a set comprehension:
# # s = {el for tup in lst for el in tup}

If order IS important, you can do mostly the same, but also have a result list to add to.

s = set()
result = []
for tup in lst:
    for el in tup:
        if el not in s:
            s.add(el)
            result.append(el)
like image 87
Adam Smith Avatar answered Sep 21 '22 06:09

Adam Smith