Convert args to flat list?

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 took from another SO answer, doesn't seem to produce correct results at all:

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

Answers


For a quick solution, just take your second function and make it recursive.

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

If you want to flatten arbitrarily nested lists you need a recursive function:

def flatten(ls):
  if isinstance(ls, list):
     return [fa for a in ls for fa in flatten(a)]
  else:
     return [ls]

(If you expect to flatten big structures this could be made more efficient by using generators instead of returning lists.)

This function can also be reused to create a function that takes multiple parameters:

def pflatten(*ls):
   return flatten(list(ls))

Checking __iter__ presence can be quite strange when flattening dictionary:

>>> def flatten(*args):
...     output = []
...     for arg in args:
...         if hasattr(arg, '__iter__'):
...             output.extend(flatten(*arg))
...         else:
...             output.append(arg)
...     return output
...
>>> adict = {1:2, 3:4, 5:6}
>>> blist = ['a', 'b', 'c']
>>> raw = [adict, blist]
>>> flatten(raw)
[1, 3, 5, 'a', 'b', 'c']

I think flatten should work for lists and tuples only:

import types

def flatten(*args):
    output = []
    for arg in args:
        if isinstance(arg, (types.ListType, types.TupleType)):
            output.extend(flatten(*list(arg)))
        else:
            output.append(arg)
    return output

adict = {1:2, 3:4, 5:6}
blist = ['a', 'b', 'c']
raw = [adict, blist]
print flatten(raw)

Solved it...

def flatlist(*args):
    lst = []
    for a in args:
        if hasattr(a, '__iter__'): lst.extend(flatlist(*a))
        else: lst.append(a)
    return lst

Need Your Help

ASP.Net 5 - OAuth bearer token (JWT) validation error

c# asp.net asp.net-core

I have been working on a system to authenticate and authorize users on my website using JSON Web Tokens. My system is just about completed, but I am running into an error when I attempt to use the [

Java UML API/Library

java api uml

Is there a Java API/Library that I can use to generate UML diagrams (Class, Sequence and Package)? I want to be able to embed the diagrams within my Java Application.