
Hello all, Many people have asked how to flatten a nested list into a one-dimensional list (e.g., see this StackOverflow thread <https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-...> ). While flattening a 2D list is relatively straightforward, deeply nested lists can become cumbersome to handle. To address this challenge, I propose adding a built-in list-flattening functionality to NumPy. By adding this feature to NumPy, the library would not only simplify a frequently used task but also enhance its overall usability, making it an even more powerful tool for data manipulation and scientific computing. The code snippet below demonstrates how a nested list can be flattened, enabling conversion into a NumPy array. I believe this would be a valuable addition to the package. See also this issue <https://github.com/numpy/numpy/issues/28079>. from collections.abc import Iterable def flatten_list(iterable): """ Flatten a (nested) list into a one-dimensional list. Parameters ---------- iterable : iterable The input collection. Returns ------- flattened_list : list A one-dimensional list containing all the elements from the input, with any nested structures flattened. Examples -------- Flattening a list containing nested lists: >>> obj = [[1, 2, 3], [1, 2, 3]] >>> flatten_list(obj) [1, 2, 3, 1, 2, 3] Flattening a list with sublists of different lengths: >>> obj = [1, [7, 4], [8, 1, 5]] >>> flatten_list(obj) [1, 7, 4, 8, 1, 5] Flattening a deeply nested list. >>> obj = [1, [2], [[3]], [[[4]]],] >>> flatten_list(obj) [1, 2, 3, 4] Flattening a list with various types of elements: >>> obj = [1, [2], (3), (4,), {5}, np.array([1,2,3]), range(3), 'Hello'] >>> flatten_list(obj) [1, 2, 3, 4, 5, 1, 2, 3, 0, 1, 2, 'Hello'] """ if not isinstance(iterable, Iterable) or isinstance(iterable, str): return [iterable] def flatten_generator(iterable): for item in iterable: if isinstance(item, Iterable) and not isinstance(item, str): yield from flatten_generator(item) else: yield item return list(flatten_generator(iterable))