Home > Blockchain >  Iterating on iterator with the rest of the values
Iterating on iterator with the rest of the values

Time:10-02

How for I get the "rest of the list" after the the current element for an iterator in a loop?

I have a list:

[ "a", "b", "c", "d" ]

They are not actually letters, they are words, but the letters are there for illustration, and there is no reason to expect the list to be small.

For each member of the list, I need to:

def f(depth, list):
  for i in list:
    print(f"{depth} {i}")
    f(depth 1, rest_of_the_list_after_i)


f(0,[ "a", "b", "c", "d" ])

The desired output (with spaces for clarity) would be:

0 a
 1 b
  2 c
   3 d
  2 d
 1 c
  2 d
 1 d
0 b
 1 c
  2 d
 1 d
0 c
 1 d
0 d

I explored enumerate with little luck.

The reality of the situation is that there is a yield terminating condition. But that's another matter.

I am using (and learning with) python 3.10

This is not homework. I'm 48 :)

You could also look at it like:

0 a 1 b 2 c 3 d
        2 d
    1 c 2 d
    1 d
0 b 1 c 2 d
    1 d
0 c 1 d
0 d

That illustrates the stream nature of the thing.

CodePudding user response:

Seems like there are plenty of answers here, but another way to solve your given problem:

def f(depth, l):
    for idx, item in enumerate(l):
        step = f"{depth * ' '} {depth} {item[0]}"
        print(step)
        f(depth   1, l[idx   1:])


f(0,[ "a", "b", "c", "d" ])

CodePudding user response:

def f(depth, alist):
  # you dont need this if you only care about first
  # for i in list: 
  print(f"{depth} {alist[0]}")
  next_depth = depth   1
  rest_list = alist[1:]
  f(next_depth,rest_list)

this doesnt seem like a very useful method though

def f(depth, alist):
  # if you actually want to iterate it
  for i,item in enumerate(alist): 
      print(f"{depth} {alist[0]}")
      next_depth = depth   1
      rest_list = alist[i:]
      f(next_depth,rest_list)

CodePudding user response:

I guess this code is what you're looking for

def f(depth, lst):
  for e,i in enumerate(lst):
    print(f"{depth} {i}")
    f(depth 1, lst[e 1:])


f(0,[ "a", "b", "c", "d" ])
  • Related