-2

I want to check if a certain number exists in a nested list

Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]

def ASearch(t, L):

if t==L:
    return True
else:

    return  ASearch(t, L[0]) or ASearch(t, L[1])

ASearch(15,Slist)

What is the problem?

Update:

The OP meant to post this:

Slist = [[[10, 20], [30, 40]], [[50, 60], [70, 80]]]

def ASearch(t, L):

    if t==L:
        return True
    return ASearch(t, L[0]) or ASearch(t, L[1])


print(ASearch(15, Slist))
print(ASearch(50, Slist))

Expected output:

False
True

Actual output:

TypeError: 'int' object is not subscriptable
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 1
    15 is not in the list so it will never return True? Your indentation is wrong? – Alan Kavanagh Nov 17 '17 at 10:54
  • 2
    @AK47 Doesn't work regardless – Ma0 Nov 17 '17 at 10:55
  • 1
    Can 2 'or'd values ever evaluate to 15? Will it always turn x or y as a True/False? – Alan Kavanagh Nov 17 '17 at 10:56
  • I think the [second answer here](https://stackoverflow.com/questions/40514139/check-if-an-item-is-in-a-nested-list) will do what you want. Using the any keyword also has the advantage of working with lists of any length, rather than explicitly slicing the list like you do above. – ConorSheehan1 Nov 17 '17 at 11:00
  • @user8956966: Please make sure you post with correct indentation. If that is the identical indentation you used in your code then please also fix it in your code! – mrCarnivore Nov 17 '17 at 11:06

2 Answers2

2

One of the few problems in your code is that it can only return True.

What you want is probably this:

def ASearch(t, L):
    if type(L) == list:
        return any(ASearch(t, l) for l in L)
    else:
        return t == L
Julien
  • 13,986
  • 5
  • 29
  • 53
0

Another approach would be flattening the list separately and then checking if the element is included in the flattened list:

def flatten(L):
    flat = []
    if isinstance(L, list):
        for item in L:
            flat += flatten(item)
    else:
        flat.append(L)
    return flat


def ASearch(t, L):
    return t in flatten(L)

You can now call your ASearch function using the element and the list: ASearch(50, nested_list).

Alternatively, you can make ASearch a lambda-function now:

ASearch = lambda t,L: t in flatten(L)
Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44