Welcome, guest | Sign In | My Account | Store | Cart

Classic / frequently asked, 'How to flatten a list, regardless the nesting.'

Python, 8 lines
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?

Created by Michael Puckett on Tue, 21 Dec 2010 (MIT)
Python recipes (4591)
Michael Puckett's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks