Skip to content Skip to sidebar Skip to footer

Search Of Element Inside A Multi-dimensional List Not Working. Any Clue

I am trying to search for an element inside a multi-dimensional list, but its not working. Anything wrong in my search ?? Below is the simple code and I tried searching using 'in'

Solution 1:

If list1 should be a list of lists, then the problem is that you are appending a list to list1, in this case, use extend instead.

If you want to search a item in a nested list (any number of levels), you can use this function

def in_nested_list(item, x):
    ifnot isinstance(x, list):
        return x == item
    else:
        return any(in_nested_list(item, ix) for ix in x)

list1 = []
list1.append([['hello'], ['blue'], ['bla']])

print list1

list1.append([['hello'], ['blue'], ['bla']])
print list1

#if'hello'in list1:
if in_nested_list('hello', list1):
    print"Found Hello"else:
    print"Not Found Hello"

Solution 2:

If you want to find 'hello' you'll have to search down one further level:

ifany('hello'in x for middle_list in list1 for x in middle_list):
    print"Found Hello"

Solution 3:

You need to go one layer deeper, like:

forlin list1:
    foritemin l:
        if'hello' in item:
            #do something

Or use list.extend()

Post a Comment for "Search Of Element Inside A Multi-dimensional List Not Working. Any Clue"