Search code examples
pythonlistenumerate

In python, given a list of lists, how do you identify the index of a matching element?


>>> birds = ['duck', 'chicken', 'goose']
>>> cats = ['tiger', 'lion']
>>> humans = ['human']
>>> at_the_zoo = [birds, cats, humans]

Given a list of lists like at_the_zoo, how do I locate which list tiger is in?

for animal in sum(at_the_zoo, []):
    if "tiger" == animal:
        print "1 help!"

For example, I can find tiger in the list of animals, and if I use enumerate, it will tell me it is at index 3. How do I figure out that it is part of element 1 of the list at_the_zoo. searching for duck will tell me element 0, etc.

Thanks!


Solution

  • I would think something like:

    def find_element(nested_lst, what):
        for idx, sublst in enumerate(nested_lst):
            try:
                idx2 = sublst.index(what)
                return (idx, idx2)
            except ValueError:
                pass
    

    should work.

    example:

    >>> def find_element(nested_lst, what):
    ...     for idx, sublst in enumerate(nested_lst):
    ...         try:
    ...             idx2 = sublst.index(what)
    ...             return (idx, idx2)
    ...         except ValueError:
    ...             pass
    ... 
    >>> birds = ['duck', 'chicken', 'goose']
    >>> cats = ['tiger', 'lion']
    >>> humans = ['human']
    >>> find_element([birds, cats, humans], 'human')
    (2, 0)
    >>> find_element([birds, cats, humans], 'gator')  # returns None if not found.
    >>> find_element([birds, cats, humans], 'tiger')
    (1, 0)
    

    It's worth noting that on average, list.index is an O(N) operation which means that lists aren't the most efficient data structure for testing membership. if your actual data supports it, it might be worthwhile to consider using a set instead.