0
votes

Possible Duplicate:
Flatten (an irregular) list of lists in Python

I have a list l = [2, 9, [1, 13], 8, 6] which I need to flatten recursively to get l = [2, 9, 1, 13, 8, 6]. I can't find a way to do so.

PS - As of writing this, I couldn't find any question matching my doubt in the Related Questions' lists. So if this is a duplicate, then kindly just point me to the old question instead of flaming me. :)

1
The dupe above not only has something that would probably answer you but there's a link to lots of questions in the question itself that have similar answers that might work as well. - Daniel DiPaolo
The solutions there use methods which I've not yet come across as I've just started learning Python. - Dharmit
Before understanding my knowledge of Python, this thread was closed. I am a newbie in Python who learns Python whenever I get free from work. I shall raise the bar but it takes time guys. I could not understand the solution on the dupe or from the answer below. Anyway, I figured out the solution myself. If this thread opens up, I shall post my solution so that it can be optimized by experts here who didn't care to know about my knowledge of Python before closing this thread. - Dharmit

1 Answers

6
votes

If you want to flatten arbitrarily nested iterables, you could try this function:

def flatten(x):
    try:
        it = iter(x)
    except TypeError:
        yield x
    else:
        for i in it:
            for j in flatten(i):
                yield j

Example:

a = [2, 9, [1, 13], 8, 6]
list(flatten(a))
# [2, 9, 1, 13, 8, 6]

Note that the function would also flatten out strings to single characters.