-3

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)

AMC
  • 2,642
  • 7
  • 13
  • 35
razorvla
  • 45
  • 7
  • 8
    You should show what you've attempted yourself. – Sayse Mar 12 '20 at 15:36
  • 3
    What have you tried, where did you fail? Additionally, do not call your variables like builtin types (`list`, `dict`, `tuple`, ...). – Jan Mar 12 '20 at 15:37
  • also relevant: https://stackoverflow.com/questions/13728023/python-2-7-check-if-a-sublist-contains-an-item – Tomerikoo Mar 12 '20 at 15:39
  • 1
    Do you ask **how to make this works**, or **oh, I thought that would work**? The earlier results in the previous comments, while the later states you actually didn't understand what the `in` operator does. – Chayim Friedman Mar 12 '20 at 15:40
  • 2
    Could your data ever have a sub-sub-list? – John Gordon Mar 12 '20 at 15:41
  • What is the issue, exactly? Have you tried anything, done any research? Stack Overflow is not a free code writing service. See: [ask], [help/on-topic], https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users. – AMC Mar 12 '20 at 18:58

3 Answers3

1

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
Mark
  • 90,562
  • 7
  • 108
  • 148
  • OP only wants it to return `True` if n matches the first element of any of the lists, not any element – Dan Mar 12 '20 at 15:44
  • 1
    Thanks @Dan, when will I learn that reading comprehension is broken before coffee. – Mark Mar 12 '20 at 15:45
1

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

Dan
  • 1,575
  • 1
  • 11
  • 17
  • This is nice, but problematic with a list like `l=[2, [3,6], [4,1,7], 5]`. `print(5 in first_elements)` => True. – Mark Mar 12 '20 at 15:53
  • @MarkMeyer from reading the question, I would say that `l=[2, [3,6], [4,1,7], 5]` should still return True, although, it's not clear – Dan Mar 12 '20 at 15:56
0

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)
Phoenixo
  • 2,071
  • 1
  • 6
  • 13