Possible Duplicate:
Flatten (an irregular) list of lists in Python
I have a python list whose elements can be letters or lists of letters.I wanted to write a function to extract all elements as below
suppose
l=['a',['b',['c']] ]
The output need to be ['a','b','c']
I thought recursion would be the correct way to do this.
The base case may be that the list contains only one element.
I tried to code this..but the output is
['a', 'b', ['c']]
Can someone please tell me what went wrong here?
def get_all_elements(mylist):
if len(mylist)==1:
return mylist[0]
else:
output=[mylist[0]]
output+=get_all_elements(mylist[1:])
return output
This seems to work Ok:
Where you went wrong is that in your solution,
mylist[0]can itself be a list (of length 1) which contains another list (of arbitrary length). In that case, you just returned it.