[Tutor] Recursively flatten the list

Dave Angel davea at ieee.org
Sat Mar 26 12:47:40 CET 2011

On 01/-10/-28163 02:59 PM, Prasad, Ramit wrote:"

 >A more important problem is that it is flattening only one level.
 >Multi-level flattening is I think not possible without using some kind
 >of recursion."
 >Not true, just requires more iterations to check each element. Each 
 >iteration could check if every element is a list and then unpack if it 
 >is a list. When you finally have an iteration that has no lists, you 
 >can end the loop.
 >Not time efficient or pretty but it would certainly work without 
 >recursion.  I am sure people on this list can provide a better answer 
 >than I can :)

Indeed, something like the following would suffice, in one "pass". 

index = 0
while index < len(mylist):
     if isinstance(mylist[index), list):
         mylist[index:index+1] = mylist[index]
     else index += 1


More information about the Tutor mailing list