Search code examples
pythonlistenumerate

Given a list of lists, find the index of the list which contains a particular item in Python


For example, I have a list of lists:

[[1,2],[3,4],[5,6]]

Given element 3, I need the index of the list it belongs to, i.e. 1.

The lists have mutually exclusive elements.


Solution

  • Here's a quick solution, although it does build a temporary list:

    >>> x = [[1,2],[3,4],[5,6]]
    >>> v = 3
    >>> [v in y for y in x].index(True)
    1
    >>>