Extract all the elements from a list of tuples and put all those unique elements in a list

Question:

codes = [('A', ['B', 'C']), ('D', ['E', 'C'])]

Output:

['A', 'B','C','D','E']

Tried Code:

n = 1
e = [x[n] for x in codes]
Asked By: Alpha Beta

||

Answers:

For the basic case shown there:

tuples = [("A", ["B", "C"]), ("A", ["B", "C"])]

unpacked = []

for current_tuple in tuples:
    # add the first element
    unpacked.append(current_tuple[0])
    # append all elements in the list to the tuple
    unpacked.extend(current_tuple[1])

for nesting of unknown depth

def get_all_elements(from_list) -> list:
    elements = []
    for item in from_list:
        if type(item) == list or type(item) == tuple:
            elements.extend(get_all_elements(item))
        else:
            elements.append(item)
            
    return elements

If all elements have a known and predictable structure e.g. 1st element is a string and 2nd element is a tuple of strings then the first case can be used. Otherwise the more complicated recursive function (second case) is required.

Answered By: Pioneer_11
from itertools import chain
list(set(list(chain.from_iterable([val for sublist in list(map(list, zip(*codes))) for val in sublist]))))
Answered By: Stackpy
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.