Here is an iterative version (originally inspired by Artsiom Rudzenka's) that modifies the list in place using slice assignment rather than creating a new list on each pass. Interestingly, only one pass through the list is needed! My use of enumerate()
is a little unorthodox; I use it to keep track of an index into a list that may be growing as I iterate over it, but don't actually use the actual list item.
def flattened(items, seqtypes=(list, tuple)):
items = items[:] # we will return a copy; remove to mutate original
for i, _ in enumerate(items):
while isinstance(items[i], seqtypes):
items[i:i+1] = items[i]
return items
print flattened([1,2,[3,4,[5,6,7,[8]]],[9],10])
Generator version:
def flattener(items, seqtypes=(list, tuple)):
items = items[:]
for i, _ in enumerate(items):
while isinstance(items[i], seqtypes):
items[i:i+1] = items[i]
yield items[i]
print list(flattener([1,2,[3,4,[5,6,7,[8]]],[9],10]))
Here is a list
subclass that has a flatten()
method. Like the sort()
and reverse()
methods, this mutates the list and returns None
.
class listy(list):
def flatten(self, seqtypes=(list, tuple)):
for i, _ in enumerate(self):
while isinstance(self[i], seqtypes):
self[i:i+1] = self[i]
lst = listy([1,2,[3,4,[5,6,7,[8]]],[9],10])
lst.flatten()
print lst
Edit: I simplified this pretty significantly from my original version. However, I see the question has been closed.