user2426320
user2426320

Reputation: 81

Recursively get each element in a list of lists (Flattening isn't applicable)

I'm creating lists of lists than can be of unlimited depth, for example:

[[[['Alpha'], ['Bravo']], ['Charlie']], [[['Delta'], ['Echo']], ['Foxtrot']]]

I'd like to get to each element in the list. It's always a left-right situation on any level.

EDIT: The reason I'm creating those lists of lists is: I've found it a convenient way to record the parent-child relations between elements. Flattening isn't applicable in this case, as it disregards the relations between elements.

Thanks.

Note: There are a couple of similar questions here, but I'm pretty sure this isn't a dupe

Upvotes: 0

Views: 42

Answers (1)

Kaushik NP
Kaushik NP

Reputation: 6781

Since flattening the list is not an option, you can traverse through the list recursively.

def traverse(l): 
    for i,ele in enumerate(l):  
       if len(ele)>1:  
          traverse(ele)  
       else:  
          print(ele)  

traverse(l)

#driver values :

IN : l = [[[['Alpha'], ['Bravo']], ['Charlie']], [[['Delta'], ['Echo']], ['Foxtrot']]] 
OUT : 
['Alpha']
['Bravo']
['Charlie']
['Delta']
['Echo']
['Foxtrot']

In case you want even the Depth of the list element, just change the function to :

def traverse(l, depth): 
    for i,ele in enumerate(l):  
       if len(ele)>1:  
          traverse(ele, depth+1)  
       else:  
          print(ele, depth+1)  

traverse(l, 0)

#driver values

OUT :
['Alpha'] 3
['Bravo'] 3
['Charlie'] 2
['Delta'] 3
['Echo'] 3
['Foxtrot'] 2

Upvotes: 2

Related Questions