Meriton Gjymshiti
Meriton Gjymshiti

Reputation: 51

Getting index of a sublist specific to an element in it

How can I get the index of a list inside of another list but, I want to find the index by using an element of that “inside” list in Python? for example I have

 [["dead"["brain.txt"],["alive",["grail.txt"]]. 

Now I want to find the index of the second list but using the element alive. So if I have an input and I write alive, it should give me the index 1, in which alive is stored.p

Upvotes: 1

Views: 65

Answers (2)

Menglong Li
Menglong Li

Reputation: 2255

How about using a class to this?

lst = [["dead", ["brain.txt"]], ["alive", ["grail.txt"]]]


class MyList(object):
    def __init__(self, lst):
        self._lst = lst

    def __getitem__(self, item):
        for idx, values in enumerate(self._lst):
            if item in values:
                return idx
        return KeyError()


print(MyList(lst)['alive'])

Upvotes: 0

Eric Duminil
Eric Duminil

Reputation: 54223

After fixing the syntax of your nested list, here's a way to get the index with next, enumerate and a list comprehension:

>>> data = [["dead", ["brain.txt"]],["alive",["grail.txt"]]]
>>> next(i for i, v in enumerate(data) if 'alive' in v)
1
>>> next(i for i, v in enumerate(data) if 'dead' in v)
0
>>> next(i for i, v in enumerate(data) if 'nothere' in v)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

You can define a default value if no index is found :

>>> next((i for i, v in enumerate(data) if 'nothere' in v), 'NotFound')
'NotFound'

Upvotes: 1

Related Questions