[Python] Traversing arbitrarily nested lists

Discussão em 'Python' iniciado por Stack, Junho 9, 2025.

  1. Stack

    Stack Membro Participativo

    So x is the value I am looking for in the nested list t. I understand what happens throughout the code and the list comprehension, what I do not understand is at what point does [5] become path, then [3,5] becomes path and finally [1,3,5] gets returned to show the final path of values.

    def findPath(t, x):
    if t[0] == x:
    return [t[0]]
    for path in [findPath(branch, x) for branch in t[1:]]:
    if path:
    return [t[0]] + path

    t = [1, [3, [4], [5]], [2]]

    findPath(t, 5)
    #returns [1,3,5]
    findPath(t, 2)
    #returns [1 ,2]


    Here is a link that helped me understand step by step, I just don't understand how the list becomes the path ultimately returning [t[0]] + path.

    Continue reading...

Compartilhe esta Página