Reputation: 1708
Say I have a list in Python:
l = [1, 2, 3, [a, [[9, 10, 11]], c, d], 5, [e, f, [6, 7, [8]]]]
I would like to clean all the nested lists so that, if they are of length 1 (just one item), the are "pulled up" out of the list, such that the revised list would look like:
l = [1, 2, 3, [a, [9, 10, 11], c, d], 5, [e, f, [6, 7, 8]]]
Naturally I can just check if len == 1
and replace that index with its contents, but... Is there a built-in way to do this?
Upvotes: 1
Views: 470
Reputation: 1122572
You could use a recursive function:
def expand_singles(item):
if isinstance(item, list):
if len(item) == 1:
return expand_singles(item[0])
return [expand_singles(i) for i in item]
return item
Demo:
>>> def expand_singles(item):
... if isinstance(item, list):
... if len(item) == 1:
... return expand_singles(item[0])
... return [expand_singles(i) for i in item]
... return item
...
>>> l = [1, 2, 3, ['a', [[9, 10, 11]], 'c', 'd'], 5, ['e', 'f', [6, 7, [8]]]]
>>> expand_singles(l)
[1, 2, 3, ['a', [9, 10, 11], 'c', 'd'], 5, ['e', 'f', [6, 7, 8]]]
Upvotes: 2