Classic / frequently asked, 'How to flatten a list, regardless the nesting.'
1 2 3 4 5 6 7 8 | def flatten(lst):
if lst:
car,*cdr=lst
if isinstance(car,(list,tuple)):
if cdr: return flatten(car) + flatten(cdr)
return flatten(car)
if cdr: return [car] + flatten(cdr)
return [car]
|
I'm new to python, coming from a diverse background with an emphasis on lisp. I frequently had to flatten lists, and have written many variants over the years. I thought I'd take a stab at a python variant. Do you see any problems with this approach? Lisp influence obvious, var naming deliberate to illuminate.
Seems to work as I want:
flatten((1,2,3,(4,5,6,(7,8))))
Result:
[1, 2, 3, 4, 5, 6, 7, 8, 1, 2]
Bueller?