1

I want to search a Specific Value (an Integer) in a List in Python where the List could possibly have a Hierarchical Structure, So there could be a List on a Specific index (e.g [1,2,[[3,4],[5,6]] here the index 2 is a list it self and there could be a list in that again), and So on, or the index of Original List could have Integer values itself (e.g [1,2,3,[4,5]] in this case index 0 is an integer..

Eventually, I want the index of the searched value w.r.t original List , otherwise if searched value is not in the list, it should give me -1...I'm using recursion for that, but i'm not having the desired results...

Here's My Code

def search_in_list(L,c1):
    index=-1
    for i in range(len(L)):
        if type(L[i])==list:
            search_in_list(L[i],c1)
        elif type(L[i])!=list:
            if c1==L[i]:
                index=i
    return index

and here's an example List [1,2,[[3,4],[5,6]] So let's say i want to search 6, then it should give me 2 because that's the index of original list on which 6 is present, but i'm having -1 instead...

Can someone dig into my code and tell me the problem and solution... Thanks in Advance

David Makogon
  • 69,407
  • 21
  • 141
  • 189
Sibghat Khan
  • 147
  • 1
  • 9

1 Answers1

4

You can make some modifications to work correctly:

def search_in_list(l, needle):
    for i, item in enumerate(l):
        if type(item) == list:
            # We found it, return current index
            if search_in_list(item, needle) >= 0: 
              return i
        else:
            if needle == item:
                return i
    return -1

The main reason it didn't work was in the recursive call. When it returned that the item was found (by returning a non negative index) you didn't return the current index.

JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
  • Thanks a Lot Buddy.....I understood the problem now and thanks for the solution... – Sibghat Khan Nov 21 '16 at 12:24
  • Can You also tell me how to change this code so that if i only need to search inside a Hierarchical List (search only those elements of original List which are list itself and return the index w.r.t original list if the element is found inside) and don't check the individual elements (of the original list which are integer itself)..... So for example L=[1,2,[3,4,5]], and i search for 5, then it should not even check the element 0 and element 1....and return me 2..........Thanks a lot again – Sibghat Khan Nov 22 '16 at 10:30
  • It's a little confusing what you ask. Why don't you open a new question where you state clearly what you want with examples? – JuniorCompressor Nov 22 '16 at 10:34