disgrating a list
George Sakkis
george.sakkis at gmail.com
Fri Sep 1 14:08:36 EDT 2006
jwaixs wrote:
> Hello,
>
> How can I disgrate (probably not a good word for it) a list? For
> example:
>
> a = [1,2]
> b = 3
> c = [a] + [b] # which makes [[1,2],3]
>
> Then how can I change c ([[1,2],3]) into [1,2,3]? I have a simple
> function for this:
> ========================
> def flatten(l):
> r = []
> s = [l]
> while len(s) > 0:
> i = s.pop()
> if i.__class__ == list:
> for c in i:
> s.append(c)
> else:
> r.append(i)
> return r
> ========================
> But this function isn't really doing it in the "python-way". Doesn't
> have python an obscure function or buildin to do this?
No, it doesn't, but it's easy to roll one on your own, e.g. using a
recursive generator; in fact, if you had searched for "flatten" in the
google group of c.l.py, you'd find this: http://tinyurl.com/ndobk
George
More information about the Python-list
mailing list