I have a nested list, like this one for example:
test = [[15, [7, [None], [11, [None], [13, [None], [None]]]], [None]], [20, [None], [None]]]
I was wanting to create another list from this with only integers contained in the nest. Which would return this:
[15, 7, 11, 13, 20]
I have made this recursive function to do what I needed to accomplish but, I couldn’t help to think this isn’t the best way to go about it. Is there a more pythonic or efficient way to do it?
def nest_search(nest, hold=[]):
for item in nest:
if isinstance(item, int):
hold.append(item)
if isinstance(item, list):
nest_search(item, hold)
return hold
>>> print nest_search(test)
[15, 7, 11, 13, 20]
The only thing I see that’s unpythonic is the default argument. See this question for why that won’t work the way your expect.
Here’s how I’d fix it:
An alternative implementation would be to make the function a generator, which yields the values one by one, rather than adding them to a list that it returns at the end. (If you do need a list, just wrap the generator call in the
listconstructor).This uses the new
yield fromsyntax introduced in Python 3.3. If you are using an earlier version, you can get the same effect by replacing the last line with: