fork download
  1. def recursive_iterator(iterable):
  2. for item in iterable:
  3.  
  4. # directly iterable types:
  5. if type(item) in (list, tuple, set, frozenset):
  6. for child_item in recursive_iterator(item):
  7. yield child_item
  8.  
  9. # other iterable types where we do not want to iterate over the item directly:
  10. elif type(item) in (dict,):
  11. for child_item in recursive_iterator(item.values()):
  12. yield child_item
  13.  
  14. # not iterable types which we want to return as they are:
  15. else:
  16. yield item
  17.  
  18.  
  19. f = (3, 4, 5, {3: 4}, [16, 7, 8])
  20. g = (1, 2, [3, 4, [5, 6], {7: 8}], 9, 10, {11: f}, {12: [1, 2, {3, 4}, [5, 6]]})
  21.  
  22. for x in recursive_iterator(g):
  23. print(x, end=" ")
Success #stdin #stdout 0.02s 9936KB
stdin
Standard input is empty
stdout
1 2 3 4 5 6 8 9 10 3 4 5 4 16 7 8 1 2 3 4 5 6