[Tutor] flattening a list

Orri Ganel singingxduck at gmail.com
Sun Jan 23 06:26:29 CET 2005


Jacob S. wrote:

> Ahh, my pitiful form of flattening a list that cheats...
>
> def flatten(li):
>     li = str(li)
>     li = li.replace("[","")
>     li = li.replace("]","")
>     li = li.replace("(","")
>     li = li.replace(")","")
>     li = "[%s]"%li
>     return eval(li)
>
> It works! It's probably just a bit slower.
>
> Jacob Schmidt
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
Actually, this doesn't even work 100% of the time. If you have a list as 
the key or value in a dictionary, it will remove the brackets, at which 
point eval will fail since the dictionary will look like

{7:8,9,10} (assuming an original dictionary of {7:[8,9,10]}), which 
results in a SyntaxError

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.



More information about the Tutor mailing list