1

It is possible to get index of particular element in list using index() method, following way (borrowed from here):

>>> ["foo", "bar", "baz"].index('bar')
1 

Is it possible to apply the same principle to nested structures (if not what is the closest most pythonic way)? The result should looks like this:

In [20]: list
Out[20]: [(0, 1, 2), (3, 4, 5)]
In [21]: list.someMagicFunctionHere(,4,)
Out[20]: 1
Community
  • 1
  • 1
Wakan Tanka
  • 7,542
  • 16
  • 69
  • 122
  • I would think the pythonic way would be to do some reading then try a few things out till it feels right. – wwii Sep 20 '15 at 02:03

2 Answers2

1

Search for the element in a container in your list:

def get_nested_index(list_, element):
    for index, container in enumerate(list_):
        if element in container:
             return index

    # If we made it here, it wasn't in any of the containers
    raise ValueError("{element} not in any element in list".format(element=element))

-

>>> get_nested_index([(0, 1, 2), (3, 4, 5)], 4)
1

You can read about enumerate here if you haven't seen it before.

Navith
  • 929
  • 1
  • 9
  • 15
0

adding to Navith's solution index...

def get_nested_index(list_, element):
    lt = []
    for index, container in enumerate(list_):
        if element in container:
             t = index, container.index(element)
        lt.append(t)
        t = ()
    return lt

print(get_nested_index([(0, 1, 4, 2), (3, 4, 5)], 4))

output [(0, 2), (1, 1)]

LetzerWille
  • 5,355
  • 4
  • 23
  • 26