Search for nested list elements

Posted on

Question :

I have a problem with a code.
I have to find a specific element (I know which element it is but I do not know its position because it is random). Under normal conditions, I would use a index and would easily get the position. The problem is that it is an array where each row is a nested list, and the index method does not search within rows. What can I do to get the position of the element I want, in that case?

    

Answer :

If you have a fixed number of nestings (eg, list of element lists) – and not arbitrary (lists of list lists …) – you can use a list understanding to “flatten it “( flatten ), and then do this search in the resulting list:

>>> x = [[1,2,3],[4,5,6],[7,8,9]]
>>> [e for l in x for e in l].index(5)
4
>>> (4//3, 4%3)
(1, 1)

However, index information is useful only if the lists are the same size … Otherwise (and given the annoying Python craze to use exceptions as a control flow) it is best to do the same function:

>>> def indice(elemento, lista):
...     for i,l in enumerate(lista):
...         try:
...             return (i, l.index(elemento))
...         except:
...             pass
...     raise ValueError('O elemento nao esta na lista')
...
>>> indice(5, x)
(1, 1)

    

Leave a Reply

Your email address will not be published. Required fields are marked *