Flattening lists

Michele Simionato michele.simionato at gmail.com
Thu Feb 5 10:33:30 EST 2009


On Feb 5, 2:17 pm, mk <mrk... at gmail.com> wrote:
> Hello everybody,
>
> Any better solution than this?
>
> def flatten(x):
>      res = []
>      for el in x:
>          if isinstance(el,list):
>              res.extend(flatten(el))
>          else:
>              res.append(el)
>      return res
>
> a = [1, 2, 3, [4, 5, 6], [[7, 8], [9, 10]]]
> print flatten(a)
>
> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>
> Regards,
> mk

Looks fine to me. In some situations you may also use hasattr(el,
'__iter__') instead of isinstance(el, list) (it depends if you want to
flatten generic iterables or only lists).



More information about the Python-list mailing list