0

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. :)

Community
  • 1
  • 1
Dharmit
  • 4,958
  • 2
  • 22
  • 28
  • 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 Mar 23 '11 at 17:27
  • The solutions there use methods which I've not yet come across as I've just started learning Python. – Dharmit Mar 23 '11 at 17:31
  • 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 Mar 24 '11 at 05:00

1 Answers1

6

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.

Sven Marnach
  • 530,615
  • 113
  • 910
  • 808