0

Possible Duplicate:
Flatten (an irregular) list of lists in Python

for instance, from:

[[1,2,3],'a',[[4],[5,6],7]]

we want to flatten/penetrate the structure and get all the elements at bottom listed in a line:

[1,2,3,'a',4,5,6,7]
Community
  • 1
  • 1
Matt
  • 741
  • 1
  • 6
  • 17

2 Answers2

2
# a recursive function to flatten arbitrary nested lists into one simple 1D list
def flatten(inlist,outlist):   
    for e in inlist:
        if isinstance(e,list) :
            flatten(e,outlist)
        else:
            outlist.append(e)

it's a practice of recursive function, :). the "outlist" here serves as a reference for return-list.

there must be better structures...

;) for example:

Matt
  • 741
  • 1
  • 6
  • 17
0

For your benefit, here is an implementation that modifies the list in-place:

def flatten_in_place(seq):
    if isinstance(seq, list):
        for index, item in reversed(list(enumerate(seq))):
            if isinstance(item, list):
                seq[index: index + 1] = fil(item)
        return seq
    else:
        return [seq]

Usage:

>>> l = [[1, 2], [3, 4], 5, 6, [7, [8, 9]]]
>>> flatten_in_place(l)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Interestingly enough, the timeit results (t = 1,000,000) show this to be slightly faster than your implementation:

flatten_in_place time: 4.88
flatten time: 5.16

I'm not sure why that is exactly. Any ideas?

Joel Cornett
  • 24,192
  • 9
  • 66
  • 88