Flattening lists

mk mrkafk at gmail.com
Thu Feb 5 09:17:19 EST 2009


Brian Allen Vanderburg II wrote:
 >> def flatten(x):
 >>     res = []
 >>     for el in x:
 >>         if isinstance(el,list):
 >>             res.extend(flatten(el))
 >>         else:
 >>             res.append(el)
 >>     return res

 >
 > I think it may be just a 'little' more efficient to do this:
 >
 > def flatten(x, res=None):
 >    if res is None:
 >       res = []
 >
 >    for el in x:
 >       if isinstance(el, (tuple, list)):
 >          flatten(el, res)
 >       else:
 >          res.append(el)
 >
 >    return res


Hmm why should it be more efficient? extend operation should not be very
costly?

Regards,
mk




More information about the Python-list mailing list