0

this is my function :

extract_unique_elements([2,[[2,4,5],"c",[[["c","d"]]]]])

which should return: {2, 4, 5, “c”, “d”} (in the form of set).

I looked for some answers but they all for 2D lists. Thank you. But now I already have a solution. thank you all for your help.

def extract_unique_elements(lst):
    unique = []
    def recursion_occurs_here(element):
        for item in element:
            if isinstance(item, list):
               recursion_occurs_here(item)
            else:
               unique.append(item)
    recursion_occurs_here(lst)
    extracted = set(unique)
    return extracted
  • 3
    So first look for how to flatten an arbitrarily nested list, then convert to a set – roganjosh Mar 21 '18 at 22:03
  • If you can't find a ready-made solution, how about trying to write your own? Please show us your attempt at solving this. – Aran-Fey Mar 21 '18 at 22:05

1 Answers1

4

You can use recursion to flatten your list:

def flatten(d):
  return {i for b in [[i] if not isinstance(i, list) else flatten(i) for i in d] for i in b}

print(flatten([2,[[2,4,5],"c",[[["c","d"]]]]]))

Output:

set(['d', 2, 4, 'c', 5])
Ajax1234
  • 69,937
  • 8
  • 61
  • 102