Home > Mobile >  How to find out if a given number is in a list of lists of numbers?
How to find out if a given number is in a list of lists of numbers?

Time:05-01

I want to make a function that finds out if a given number is in a list of lists of numbers. How do I fix the following code so that it works for a list consisting of lists?

lst = [[1, 2], [3, 4],[5, 6, 7]]
num = 9

def in_list_of_list(lst: list) -> bool:

    i = 0

    while i < len(lst) and lst[i] != num:
        i = i   1
    return i < len(lst)
    
print(in_list_of_list(lst))

CodePudding user response:

You can flatten the list first, and then check easily in the flat one:

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

num = 9


def in_list_of_list(lst: list) -> bool:
    flat_list = [item for sublist in lst for item in sublist]
    return num in flat_list


print(in_list_of_list(lst))

CodePudding user response:

you ask if the item is inside any of the elements of the list

def in_list_of_list(lst: list, item:object) -> bool:
    for sublist in lst:
        if item in sublist:
            return True
    return False

and a quick test

>>> lst = [[1, 2], [3, 4],[5, 6, 7]]
>>> in_list_of_list(lst, 9)
False
>>> in_list_of_list(lst, 7)
True
>>> 

CodePudding user response:

lst = [[1, 2], [3, 4],[5, 6, 7]]
num = 9

def in_list_of_list(lst: list) -> bool:
    new_lst = []
    for a in lst:
        new_lst.extend(a) # add element from the inner list to new_list.
    return num in new_lst  # return True if the num inside the list else False.

print(in_list_of_list(lst))
  • Related