Skipping every other value in nested tuple

Viewed 182

I am trying to skip over every other list in my nested list.

filled_list = [1,2,3,[11,2,3,[111,2,3,[1111,2,3,4]]]]

def iterative_list(value):
    while isinstance(value[-1], list):
        a, *_, value = value
        yield a
    yield value[0]

z = iterative_list(filled_list)

How can I do that so the output goes from

[1, 11, 111, 1111] Parsing a list iteratively.

to

[1, 111,] Parsing a list iteratively.

I know the concept that you can skip over every other element from a list with [::2] notation, but how can I apply this to a nested list?

3 Answers

Append all as to a list, then return the list, like:

def iterative_list(value):
   l=[]
   while isinstance(value[-1], list):
       a, *_, value = value
       l.append(a)
   l.append(a)
   return l[::2]

And now:

print(iterative_list(filled_list))

Is:

[1, 111]

You can use a try-except block in an infinite loop to keep getting the inner-inner list until it catches a TypeError or IndexError:

def iterative_list(value):
    while True:
        try:
            yield value[0]
            value = value[-1][-1]
        except (TypeError, IndexError):
            break

so that list(iterative_list(filled_list)) returns:

[1, 111]

Generator with recursion:

def iterative_list(value):
    try:
        yield value[0]
        yield from iterative_list(value[-1][-1])
    except TypeError:
        return  

Example:

list(iterative_list(filled_list))
Out: [1, 111]
Related