[Chicago] Resolving lists within lists within lists within .....

Robare, Phillip (TEKSystems) proba at allstate.com
Thu Feb 18 19:48:19 EST 2016

Aaron, unlike Massimo’s elegant one-liner you don’t check that what you are iterating over is a list.  Since Python will happily iterate over strings, dictionaries, and much more you quickly get into problems when the list includes more types than lists and numbers.  I recount this from experience when I tried to throw together a flatten routine and pass it a data structure that I got from loading a JSON string.

Phil Robare


On Thu, Feb 18, 2016 at 1:43 PM, Aaron Elmquist <elmq0022 at umn.edu<mailto:elmq0022 at umn.edu>> wrote:
Here's one more version for you and the rest of the list. It's based on Brad's code.  I will let you think about why this version might be better or worse.  Also, recursion is great.  It's just too bad it's not one of python's strong points.

def flatten(lst):
    for item1 in lst:
        if hasattr(item1, '__iter__'):
            for item2 in flatten(item1):
                yield item2
            yield item1

print([x for x in flatten([1, [2,3,[4,5,6,[7,8,9]]]]) if x%2 == 1])

y = flatten([1, [2,3,[4,5,6,[7,8,9]]]])

On Wed, Feb 17, 2016 at 9:48 PM, DiPierro, Massimo <MDiPierro at cs.depaul.edu<mailto:MDiPierro at cs.depaul.edu>> wrote:
here is a one liner:

def flatten(x):
    return [z for y in x for z in flatten(y)] if isinstance(x,list) else [x]

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20160219/72fb55b6/attachment.html>

More information about the Chicago mailing list