I have a list l = [2, 9, [1, 13], 8, 6]
. How can I flatten it recursively to get l = [2, 9, 1, 13, 8, 6]
?
Asked
Active
Viewed 3,772 times
0

Karl Knechtel
- 62,466
- 11
- 102
- 153

Dharmit
- 5,498
- 2
- 27
- 30
-
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 Answers
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
- 574,206
- 118
- 941
- 841