1

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

I wanted a solution to list/print all the items in a nested list (with arbitrary nesting level). Here is what I came up with:

items = []
def getitems(mylist):
    for item in mylist:
        if type(item) is list:
            getitems(item)
        else:
            items.append(item)
    return items

Sample output:

foo=['foo','bar',['foo','bar','baz'],'spam',['ham','eggs','salami']]

In [8]: getitems(foo)
Out[8]: 
['foo',
 'bar',
 'foo',
 'bar',
 'foo',
 'bar',
 'baz',
 'spam',
 'ham',
 'eggs',
 'salami']

Is this a good solution? Or is there a better approach?

Community
  • 1
  • 1
  • 2
    I think you want to post that on http://codereview.stackexchange.com/ . Otherwise, it looks good to me. – JosefAssad Aug 09 '12 at 10:24
  • 6
    Looks good, you might change the `type(item) is list` to `isinstance(item, list)`. Also note that there is a recursion depth limit which is by default is 1000. – Zaur Nasibov Aug 09 '12 at 10:26
  • Thanks for the isinstance tip! –  Aug 09 '12 at 10:27

1 Answers1

0

This might be a bit pedantic, but you could pass the accumulator list as an optional argument. This way you don't have any global variables lying a round and avoid possible issues when you call the function twice and forgot to clear it after the first call:

def getitems(mylist, acc = None):
    if acc is None: acc = []
    for item in mylist:
        if type(item) is list:
            getitems(item, acc)
        else:
            acc.append(item)
    return acc
ddk
  • 1,813
  • 1
  • 15
  • 18
  • You should never put an empty list (or any other mutable object) as defualt parameter to a function in Python. It is one of the language's greatest pitfalls. – jsbueno Aug 09 '12 at 11:45
  • 1
    Use `def getitems(mylist, acc=None):` and inside the body `if acc is None: acc = []` instead. – jsbueno Aug 09 '12 at 11:46
  • Thank you for pointing that out. I updated my answer. Could you please explain why using mutable data as default parameters are a bad idea? – ddk Aug 09 '12 at 11:52
  • 1
    The issue is that default parameters get evaluated once, when the function is defined. Any changes made to the default parameter persist in subsequent calls to the function. – Joe Day Aug 09 '12 at 11:58
  • Thanks! I found [an old blog post](http://effbot.org/zone/default-values.htm) that discusses the issue in some detail. – ddk Aug 09 '12 at 12:07
  • See http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python for the best way of doing this. This question should be closed as duplicate anyway, awaiting two more votes – jamylak Aug 10 '12 at 04:50