# How to deep flatten a list of messy arrays?

I have a Python list/array of really messy lists/arrays that either contains a list, array, or an empty list/array. Is there a simple operation I can use to completely flatten it to return me a 1D array?

Here would be an example that might not be correct

``````a = np.array([[1,2,3],
[],
[np.array([1,2,3])],
[np.array([1,2,[]])]])
``````

I say might not be correct because I cant think of a way to make it even messier. There would only be numbers in the data. No strings etc.

But all I need is to convert it to a 1D array where each entry contains a single value; neither a list nor an array. Is there such a function or do I need to iterate the the array and do a check for every element?

### >Solution :

You could write a recursive function that goes through the nested iterable items to flatten the structure:

``````def flatten(a):
try:
return [item for flat in map(flatten,a) for item in flat]
except:
return [a]
``````

ouput:

``````import numpy as np

a = np.array([[1,2,3],
[],
[np.array([1,2,3])],
[np.array([1,2,[]])]])

print(flatten(a))

[1, 2, 3, 1, 2, 3, 1, 2]
``````