Search code examples
pythonpython-3.xlistnested-lists

I want to traverse a nested list and find index of that list


I want to traverse over the nested list below, search for a number and then print the index value of that entire list, i.e: my_foo(lst=[1, 3, 'Test', 5, 7], number=3) returns 1.

This is my list:

my_list = [['Hello', 'World','!'], [1, 3, 'Test', 5, 7], [2, 4]]

I want to search for example 1, and if that's True, print its list index.


Solution

  • Here is a function that takes a list and a function as a key:

    from typing import List, Callable
    
    my_list = [['Hello', 'World','!'],[1, 3, 'Test', 5, 7],[2, 4]]
    
    
    def nested_index(l: List, key: Callable[[List], bool]):
        for i, v in enumerate(l):
            if key(v):
                return i
        raise ValueError
    

    Example:

    nested_index(my_list, lambda l: 1 in l) -> 1
    nested_index(my_list, lambda l: "hello" in l) -> 0
    nested_index(my_list, lambda l: "foo" in l) -> ValueError