How do I unnest a tuple with mixed types?

Question:

I’m trying to flatten a tuple with mixed types into a list. The following function does not produce the desired output:

a = (1, 2, 3, ['first', 'second'])
def flatten(l): 
return flatten(l[0]) + (flatten(l[1:]) if len(l) > 1 else []) if type(l) is list else [l]

>>> flatten(a)
[(1, 2, 3, ['first', 'second'])]
>>> flatten(flatten(a))
[(1, 2, 3, ['first', 'second'])]
>>> [flatten(item) for item in a]
[[1], [2], [3], ['first', 'second']]

the output should be:

>>> [1, 2, 3, 'first', 'second']
Asked By: Bob

||

Answers:

def flatten(l):
    if isinstance(l, (list,tuple)):
        if len(l) > 1:
            return [l[0]] + flatten(l[1:])
        else:
            return l[0]
    else:
        return [l]

a = (1, 2, 3, ['first', 'second'])

print(flatten(a))

[1, 2, 3, ‘first’, ‘second’]

Answered By: Rahn
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.