0

I'm using python 3 and i work with PyMongo.

PyMongo allow me to iterate over collections from database like this :

List['tomato',['apple',['carpet','dishwasher','mister T',[... etc.. etc..]],'coke'],'pie']

i'm currently using for loop with a maximum of 4 levels. And that's very hard to maintain and understand.

So i want to iterate recursively in all nested array from first array to the last nested array.

Thank you :)

Jude

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    You want to [*flatten* your list](https://stackoverflow.com/questions/2158395/) and then iterate the result. – Tomalak Aug 12 '19 at 16:11
  • It would be easier to understand your question if you were able to show your code. – PixelEinstein Aug 12 '19 at 16:11
  • Welcome to Stackoverflow, please read [How To Ask](https://stackoverflow.com/help/how-to-ask). Pay special attention to [How To Create MCVE](https://stackoverflow.com/help/mcve). Make sure you tag your question with proper labels (programming language, relevant technologies etc). The more effort you'll put into posting a good question: one which is easy to read, understand and which is [on topic](https://stackoverflow.com/help/on-topic) - the chances are higher that it will attract the relevant people and you'll get help even faster. Good luck! – Nir Alfasi Aug 12 '19 at 16:15
  • @Tomalak exactly what i want thank you :) ! – SuperJudeFruit Aug 12 '19 at 16:20

1 Answers1

0

If you simply want to flatten your list, you can recurse it with a function like below. It calls itself every time it ecounters a nested list and keeps saving the elements to a result list that is returned in the end.

def recurse(in_list):
    result=[]
    for e in in_list:
        if type(e)==list:
            result+=recurse(e)
        else:
            result+=[e]
    return result

Once you create the function you can use it like this:

x=['tomato',['apple',['carpet','dishwasher','mister T'],'coke'],'pie']
recurse(x)

Output

['tomato', 'apple', 'carpet', 'dishwasher', 'mister T', 'coke', 'pie']

It will only handled nested lists, but you could modify the code to take care of other types (dictionaries, sets, etc..)

Ernesto
  • 605
  • 1
  • 13
  • 30