Home > front end >  In Python, I am having trouble finding out if an item is in a list
In Python, I am having trouble finding out if an item is in a list

Time:05-23

I am trying to search nested lists for items. The lists will have a mixture of strings and numbers...which don't have to be integers I suppose. Separate from the program I am trying to write, I made a small set of code just to play around with searching lists, but nothing seems to work. I am new to this so be easy on me. I appreciate any direction here. The contents of the list print, and the variable for the user input section does set appropriately. However, I am getting "False" when I would expect "True", and my 'if' statements that try to see if the item exists keeps telling me that it does not.

Here is the code of my test file:

test_list=[['a','b','c',1,2,3],['d','e','f',4,5,6]]

print('contents of the list:')
print (test_list)

print('Checking if "a" is in the list:')
if ('a' in test_list)==True:
    print('yes its in the list')
else:
    print('no it is not in the list')
print('')

print('will this return True?:')
print('a' in test_list)


# trying a user entered value, which
# is directly related to what I want to do
print('now for a user entered value:')
item=input ('enter-->')
if ((item) in test_list)==True:
    print('yes its in the list')
else:
    print('no it is not in the list')
print('')

# shows the user's entry, to show that at least
# the 'item' variable had been set to the value.
# This does show the value entered.
print('The entered number was',item)
print ((item) in test_list)

Thanks again!

CodePudding user response:

You are getting False for if item in test_list because test_list is a list of lists, and you are only searching the first "level". Use a list comprehension to search nested lists:

if [item in sublist for sublist in test_list]:
    print("Found!")

Also, keep in mind that input() always returns a str, so you won't be able to search your numeric list members unless you cast it to an int, or turn all the list items into strings.

CodePudding user response:

For a recursive search "in depth" (not only at the first level) you can use a recursive function like this:

def search_recursive(el, l):
    if el in l:
        return True
    for e in l:
        if type(e) == list:
            return search_recursive(el, e)
    return False
  • Related