how to test if an integer is in a sub-list in a list

144 views Asked by At

I'd like to test if 3 is the first number of the element (an integer or the first of a sub-list) like this :

lst=[2, [3,6], [4,1,7]]
3 in lst

The result should be True because 3 is the first element of [3,6].

Btw: my dataset won't make my list like [3, [3,7]] (alone and in a sublist)

3

There are 3 answers

0
Phoenixo On

You can iterate over the List, and check if sub-elements sub is a list or an integer, and return your desired result :

L = [2, [3,6], [4,1,7]]
num = 2
res = False
for sub in L:
    if isinstance(sub, list):
        if num in sub:
            res = True
            break
    else:
        if num == sub:
            res = True

print(res)
2
Mark On

You can do this with a pretty simple recursive function like:

l =[2, [3,6], [4,1,7]]

def inList(l, n):
    if isinstance(l, list):
        return l[0] == n or any(inList(member, n) for member in l[1:])
    else:
        return False

inList(l, 3) # True
inList(l, 9) # False
inList(l, 2) # True

This has the advantage of digging into deeply nested lists too:

l =[2, [3,6], [4,1,[9,[5]], 7]]
inList(l, 5) # True
2
Dan On

Assuming no sub-sub-lists:

l=[2, [3,6], [4,1,7]]
first_elements = [i[0] if isinstance(i, list) else i for i in l]  # [2, 3, 4]
print(3 in first_elements)

Output:

True