0

I want to flatten a list whatever the values of list are:

Example:

[1, 2, 1] --> [1, 2]

[[1, 2], [2, 1] --> [1, 2]

Now I have a code which have very cases depending of the type of the objects in the list (first example numbers, second example list).

Is there a universal solution?

somenxavier
  • 1,206
  • 3
  • 20
  • 43
  • 1
    What actually is the rule that needs to be applied? It seems like we only want unique values - why not represent the result as a `set`? Does the order of the output matter? If so, how should it be ordered? It seems like you want to get "leaf" elements from a nested input - correct? Arbitrarily nested, or only down to a certain level? What about other container types, such as tuples? What about strings? – Karl Knechtel Feb 07 '23 at 17:16
  • That said, this seems like pretty straightforwardly a combination of a) flattening and b) removing duplicates, both of which are **extremely** common problems with canonical duplicates. Please see https://stackoverflow.com/questions/952914 and https://stackoverflow.com/questions/2158395 and https://stackoverflow.com/questions/7961363 and https://stackoverflow.com/questions/480214, and figure out what is applicable to the actual question. – Karl Knechtel Feb 07 '23 at 17:20

1 Answers1

0

You can write a function to recursively flatten lists, like so:

def flatten_list(input_list):
    flattened = []
    for item in input_list:
        if isinstance(item, list):
            flattened_item = flatten_list(item)
            flattened.extend(flattened_item)
        else:
            flattened.append(item)
            
    return list(set(flattened))

Using this function, we'd get:

flatten_list([1, 2, 1]) --> [1, 2]
flatten_list([[1, 2], [2, 1]]) --> [1, 2]
Leen
  • 13
  • 3