[Tutor] Recursively flatten the list

Dharmit Shah shahdharmit at gmail.com
Thu Mar 24 06:10:44 CET 2011


Hello,

I am learning Python and yesterday I cam across a definition wherein I was
supposed to flatten a list recursively. I am getting the solution properly
but wanted to know if I can optimize the code further.

#!/usr/bin/env python
new_list=[]
def flatten(num_list):
    """
      >>> flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]])
      [2, 9, 2, 1, 13, 2, 8, 2, 6]
      >>> flatten([[9, [7, 1, 13, 2], 8], [7, 6]])
      [9, 7, 1, 13, 2, 8, 7, 6]
      >>> flatten([[9, [7, 1, 13, 2], 8], [2, 6]])
      [9, 7, 1, 13, 2, 8, 2, 6]
      >>> flatten([[5, [5, [1, 5], 5], 5], [5, 6]])
      [5, 5, 1, 5, 5, 5, 5, 6]
    """
    global new_list
    for i in num_list:
        if type(i) == type([]):
            new_list = flatten(i)
        else:
            new_list.append(i)
    tmp = new_list
    new_list=[]
    return tmp

if __name__=="__main__":
    import doctest
    doctest.testmod()

PS - My knowledge of Python is still very basic and I am trying to dive into
it as deeper as I can. Solutions on Stackoverflow.com were beyond my
understandability.

-- 
Regards

Dharmit Shah
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110324/9dc47ec7/attachment.html>


More information about the Tutor mailing list