Spread list

OSCC · Python, List · Sep 15, 2020

Flattens a list, by spreading its elements into a new list.

  • Loop over elements, use list.extend() if the element is a list, list.append() otherwise.
def spread(arg):
  ret = []
  for i in arg:
    ret.extend(i) if isinstance(i, list) else ret.append(i)
  return ret
spread([1, 2, 3, [4, 5, 6], [7], 8, 9]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Recommended snippets

  • Merge lists

    Python, List

    Merges two or more lists into a list of lists, combining elements from each of the input lists based on their positions.

  • Groups the elements of a list based on the given function and returns the count of elements in each group.

  • Groups the elements of a list based on the given function.