Skip to content Skip to sidebar Skip to footer

How To Find A Given Element In Nested Lists?

This is my iterative solution: def exists(key, arg): if not arg: return False else: for element in arg: if isinstance(element,list):

Solution 1:

defexists(k, l):
    ifnotisinstance(l, list):
        returnFalseif k in l:
        returnTruereturnany(map(lambda sublist: exists(k, sublist), l))

Solution 2:

If we consider these cases:

  • my_list is empty: the key isn't found
  • my_list is not a list: the key isn't found
  • my_list is a non-empty list (two cases):
    • my_list[0] is the key: it was found
    • otherwise, look for the key in both my_list[0] and my_list[1:]

the code would be

def exists(key, my_list):
    ifnot isinstance(my_list, list) ornot my_list:
        returnFalsereturn (my_list[0] == keyor exists(key, my_list[0]) 
            or exists(key, my_list[1:]))

or even

def exists(key, my_list):
    return (isinstance(my_list, list)
            and len(my_list) > 0 
            and (my_list[0] == key
                 or exists(key, my_list[0])
                 or exists(key, my_list[1:])))

Solution 3:

The logic is to iterate each element in your list and check:

  • if list: call the function again with the sub-list.
  • if equals the key: return True
  • else: return False

Below is sample code to find whether key exists or not in nested list

defexists(key, my_list):
    for item in my_list:
        ifisinstance(item, list):
            if exists(key, item):  # <--Recursive CallreturnTrueelif item == key:
            returnTruereturnFalse# Example>>> my_list = [[[1, 2, 3, 4, 5], [6, 7,]], [8, 9], 10]
>>> exists(2, my_list)
True>>> exists(6, my_list)
True>>> exists(8, my_list)
True>>> exists(10, my_list)
True>>> exists(11, my_list)
False

Solution 4:

You are close. You only have to check if arg[0] is a sublist and if make a new call. Next you are missing a loop to run through all items of the list. This should work.

defexists(key, arg):
    for item in arg:
        ifisinstance(item, list):
            # Recursive call with sublistif exists(key, item):
                returnTrueelse:
            if item == key:
                returnTruereturnFalse

Solution 5:

Thanks everyone for your help, here is the answer that I have figured out. While it does not look as elegant as most of the answers that were already provided, this answer is the only answer that my lab instructor will accept as it is a pure functional programming method meaning no side effects or for loops:

def exists(key, seq):
    ifnot seq:
        return False
    elif seq[0]==key:
        return True
    if isinstance(seq[0],list):
        return(exists(key,seq[0]) orexists(key,seq[1:]))

    else:
        returnexists(key,seq[1:])
    return False
print(findkey("s", ["g","t", "e", ["s"], ["l","k","s",["d","f"],"w"], "o"]))

Post a Comment for "How To Find A Given Element In Nested Lists?"