flat_list = [item for sublist in l for item in sublist]
#which is equivalent to this
flat_list = []
for sublist in l:
for item in sublist:
flat_list.append(item)
nested_lists = [[1, 2], [[3, 4], [5, 6], [[7, 8], [9, 10], [[11, [12, 13]]]]]]
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
flatten(nested_lists)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
from collections.abc import Iterable
def flatten(l):
for el in l:
if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
else:
yield el
from typing import Iterable
# flatten any number of nested iterables (lists, tuples)
def flatten_iterables(iterable: Iterable) -> list:
"""Convert iterables (lists, tuples) to list (excluding string and dictionary)
Args:
iterables (Iterable): Iterables to flatten
Returns:
list: return a flattened list
"""
lis = []
for i in iterable:
if isinstance(i, Iterable) and not isinstance(i, str):
lis.extend(flatten_iterables(i))
else:
lis.append(i)
return lis
# if your list is like this
l = [['Adela', 'Fleda', 'Owen', 'May', 'Mona', 'Gilbert', 'Ford'], 'Adela']
# then you
a = []
for i in l:
if type(i) != str:
for x in i:
a.append(x)
else:
a.append(i)