0

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

user2426320
  • 81
  • 1
  • 11
  • 1
    process **how**? https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists will iterate over the elements... using generators for example... or do you mean you want to process the **lists**... – Antti Haapala -- Слава Україні Oct 15 '17 at 18:02
  • Possible duplicate of [Flatten (an irregular) list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists) – Kaushik NP Oct 15 '17 at 18:04
  • Why I'm creating those lists of lists: I've found it a way to record the parent-child relations between elements. Flattening isn't applicable in this case, as it disregards the relations between elements. Is the downvote really applicable, @KaushikNP? – user2426320 Oct 15 '17 at 18:14
  • Whats the question – Nick is tired Oct 15 '17 at 18:22
  • @NickA Recursively get (and print, for example) each element in the list – user2426320 Oct 15 '17 at 18:24
  • @user2426320 , seems fair I do a +1 there. – Kaushik NP Oct 15 '17 at 18:37
  • You wrote,"I'd like to get each element in the list". The reason for the other comments giving pushback is that the enumerate IS a flattened list. – Rookie Oct 15 '17 at 19:03
  • I do understand that you want to keep the original list as it is, i.e. not flattened. But could you please explain the difference between getting each element and flattening? – VPfB Oct 15 '17 at 21:08

1 Answers1

2

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
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60