2

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
Community
  • 1
  • 1
damon
  • 8,127
  • 17
  • 69
  • 114

3 Answers3

3

This seems to work Ok:

def flatten(iterable):
   out = []
   for i in iterable:
      if hasattr(i,'__iter__'):
         out.extend(flatten(i))
      else:
         out.append(i)
   return out

l=['a',['b',['c']] ]   
print flatten(l)

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
1

When you check to see if mylist is of length 1, you don't check for the case where its contents are a list. Here's an example that will highlight your problem.

get_all_elements([1, [2, [3, 4]]])

If you want a complete solution, Flattening a shallow list in Python and Comprehension for flattening a sequence of sequences? are good places to look.

Community
  • 1
  • 1
nmichaels
  • 49,466
  • 12
  • 107
  • 135
0

this will work on up to 3 levels deep, if the depth is arbitrary i don't think you'll be able to use a list comprehension.

[grandchild for parent in l for child in parent for grandchild in child]
Mike Corcoran
  • 14,072
  • 4
  • 37
  • 49