Home > database >  Why won't "if this in thislist" return True when user inputs "this" and &qu
Why won't "if this in thislist" return True when user inputs "this" and &qu

Time:10-08

I'm trying to understand how some code works so I've made my own simple code that should act like how the more complex code works. However, it seems that I'm missing something. I made a simple program to pass a "trigger" to compare to my list.

def function(findme, thislist):
  print("FindMe: {}".format(findme))
  print("In This List: {}".format(thislist))
  if findme in thislist:
    print("In!")
    return thislist

while(True):
  find = []
  list = []
  find.append(input("Input number to find: "))
  print("Find: {}".format(find))
  list.append(input("Input 1st number: "))
  list.append(input("Input 2nd number: "))
  print("List: {}".format(list))
  result = function(find, list)
  print(result)
  if result is not None:
    print("returned list")
    print(list)
  else:
    print("nothing returned")

The code finishes returning None and printing "nothing returned". I input 1 as find and 1, 2 as list. What am I missing here?

p.s. I'm new to python and stack overflow, forgive my messy post :x

CodePudding user response:

You cannot search if a list contains a sublist that way.

If you want to check if multiple elements are in the list, then you can do this instead

if (all(x in thislist for x in findme)):
    print ("Sublist in the mainlist")
    return thislist

This is one way to do it, if you do not have to compare lists, then you could simply use the code which you have just replace findme with findme[0]

CodePudding user response:

The problem is, that the search value is a list itself. So you check if a list with one value is in the list with the values you want to find. It is not. The one value in the search list might be in the list with the values.

So you should use a single value as your search term.

I optimized the names of some variables, used f-strings for formatting and used fixed values for filling the list so you can test it faster.

def is_in_list(findme, data):
    print(f"FindMe: {findme}")
    print(f"In This List: {data}")
    if findme in data:
        print("In!")
        return True
    return False


find = input("Input number to find: ")
print(f"Find: {find}")
data = []
data.append("42")
data.append("23")
print(f"List: {data}")
if is_in_list(find, data):
    print(data)
else:
    print("nothing returned")

One more change. It doesn't make much sense to return the same list from the function that you put in there as a parameter. So I used return values of True and False instead.

  • Related