I\'ve been working with some relatively complex arrays such as:
array = [ \"1\", 2, [\"4\", \"5\", (\"a\", \"b\")], (\"c\", \"d\")]
and I was l
What you want is something like:
def myindex(lst, target):
for index, item in enumerate(lst):
if item == target:
return [index]
if isinstance(item, (list, tuple)):
path = myindex(item, target)
if path:
return [index] + path
return []
Being recursive, this will deal with arbitrary depth of nesting (up to the recursion limit).
For your example array
, I get:
>>> myindex(array, "a")
[2, 2, 0]
As Adam alludes to in the comments, explicitly checking instance types isn't very Pythonic. A duck-typed, "easier to ask for forgiveness than permission" alternative would be:
def myindex(lst, target):
for index, item in enumerate(lst):
if item == target:
return [index]
if isinstance(item, str): # or 'basestring' in 2.x
return []
try:
path = myindex(item, target)
except TypeError:
pass
else:
if path:
return [index] + path
return []
The specific handling of strings is necessary as even an empty string can be iterated over, causing endless recursion.