Reputation: 3535
This question differs from Converting list of lists / nested lists to list of lists without nesting (this yields a very specific set of responses that do not address my situation) and also from the many "flatten list of lists to list" answers out there.
I want to take a list of lists, some of which are in turn lists of lists and "flatten" to a list of lists (not just a list!).
As a concrete example, I want to go from this:
my_list_of_lists = [[1, 2, 3], [[9, 10], [8, 9, 10], [3, 4, 6]], [11, 12, 13]]
to this
target_list_of_lists = [[1, 2, 3], [9, 10], [8, 9, 10], [3, 4, 6], [11, 12, 13]]
(In a visual sense, I want to turn all [[
and ]]
inside the outer list into [
and ]
respectively.)
Upvotes: 3
Views: 291
Reputation: 6506
Here's one way to do it:
def flatten(lst, dh=None):
# Added so user does not need to pass output list
if (dh is None):
dh = []
for elem in lst:
# Will not try to iterate through empty lists
if elem and (isinstance(elem[0], list)):
flatten(elem, dh)
else:
dh.append(elem)
return dh
my_list_of_lists = [[1, 2, 3], [[9, 10], [8, 9, 10], [3, 4, 6]], [11, 12, 13]]
target_list_of_lists = flatten(my_list_of_lists)
print(target_list_of_lists)
Output:
[[1, 2, 3], [9, 10], [8, 9, 10], [3, 4, 6], [11, 12, 13]]
This will work for lists of any length and any depth.
Upvotes: 4