Convert args to flat list?

Posted by Mark on Stack Overflow See other posts from Stack Overflow or by Mark
Published on 2010-03-29T06:48:40Z Indexed on 2010/03/29 6:53 UTC
Read the original article Hit count: 318

Filed under:
|

I know this is very similar to a few other questions, but I can't quite get this function to work correctly.

def flatten(*args):
    return list(item for iterable in args for item in iterable)

The output I'm looking for is:

flatten(1) -> [1]
flatten(1,[2]) -> [1, 2]
flatten([1,[2]]) -> [1, 2]

The current function, which I from another SO answer doesn't seem to produce correct results at all:

>>> flatten([1,[2]])
[1, [2]]

I wrote the following function which seems to work for 0 or 1 levels of nesting, but not deeper:

def flatten(*args):
    output = []
    for arg in args:
        if hasattr(arg, '__iter__'):
            output += arg
        else:
            output += [arg]
    return output

© Stack Overflow or respective owner

Related posts about python

Related posts about list