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]
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.
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.
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.
Sets are data structures that cannot contain any duplicate elements. When you convert a list into a set, all the duplicates will be removed.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With