Finding items inside a list

Viewed 57

Trying to make a program that always finds the two even from a list in a list (at least from the top level list) . And this is what I have so far.

List_Test = [[2]]

if 2 in List_Test:
    print("Found!")
elif 2 in List_Test[0][0]:
    print("Found in an inner list!")
elif 2 not in List_Test:
    print("Not Found.")

I keep coming up with a

TypeError of : argument of type 'int' is not iterable 

what am I doing wrong?

2 Answers

You can try iterating over all elements inside List_Test

List_Test = [[2], 2, [1,3]]

def check(row):
    if type(row) == int:
        return "Found!" if row == 2 else "Not Found."
    elif type(row) == list and 2 in row:
        return "Found in an inner list!"
    else:
        return "Not Found."

print([check(row) for row in List_Test])

Considering you can have more than one elements in the list, try the below code.

def check_for_element(list_, element):
    for i in list_:
        if i == element:
            print("Found!")
            return
        elif type(i) is list and 2 in i:
                print("Found in an inner list!")
                return
    print("Not Found")

check_for_element([3, 7, [9], [3, 2, 4]], 2)

Output:

Found in an inner list!

Note: elif 2 not in List_Test is redundant and not required.

Related