Combining Tuples into a List

Question:

I have a list of tuples:

[(1,2), (5,10), (2,5)]

And I would like to get a list of unique numbers

[1,2,5,10]

May I know how can I achieve that?

Asked By: Ashtart

||

Answers:

You can use numpy to do it this way:

import numpy as np

x = [(1,2),(5,10),(2,5)]
result = np.array(x).reshape(-1)

If you want to get unique values, use set() like this:

result = set(np.array(x).reshape(-1))
Answered By: milkwithfish

Will this work? I’ve appended each item to a new list, then use set() to get the unique items

new_lis = []
lis = [(1,2),(5,10),(2,5)]
for x,y in lis:
    new_lis.append(x)
    new_lis.append(y)
    
result = list(set(new_lis))

[1, 2, 10, 5]
Answered By: Adrian Ang

one-line solution:

tuples_list = [(1,2), (5,10), (2,5)]
res = sorted(list(set(sum(tuples_list, ()))))
Answered By: AmirMohammad Babaei
import itertools

L = [(1,2), (5,10), (2,5)]

flat_no_dupes = set(itertools.chain.from_iterable(L))

Using itertools chain from iterable to flatten the list, and making a set to remove duplicates.

Answered By: TessellatingHeckler

I strongly suggest you use a set comprehension to achieve this result. The set comprehension iterates over the tuples, then over the values in each tuple. We build a set from these values y.

a = [(1,2), (5,10), (2,5)]
{y for x in a 
   for y in x}
# {1, 2, 10, 5}
Answered By: Chris

A version which respects the insertion order:

[(1,2), (5,10),(2,5)] -> [1, 2, 5, 10]

[(5,10), (2,5), (1,2)] -> [5, 10, 2, 1]

l = [(5,10),(2,5), (1,2)]

# flat list
l_flat = [i for pair in l for i in pair]

# dictionary of value-position pairs (1st occurence only)
d = dict.fromkeys(l_flat, None)
for i, v in enumerate(l_flat):
    if d[v] is not None:
        continue
    d[v] = i

# order per position and get values
res = [k for k, _ in sorted(d.items(), key=lambda p: p[1])]

# check result
print(res)
Answered By: cards
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.