flatten_nested_list.py

2024-07-05

Here's a neat bit of code to flatten a nested list in Python
def flatten(arg):
  if isinstance(arg, list):
    return [x for item in arg for x in flatten(item)]
  return [arg]

Unpacked, it can look like this:

def flatten(arg):
  if isinstance(arg, list):
    flatlist = []
    for item in arg:
      if isinstance(item, list):
        for x in flatten(item):
          flatlist.append(x)
      else:
        flatlist.append(item)
    return flatlist
  return arg