89DEVs

Python: How to check if string is in list?

How to check if a string is in a list?

How to check if a string is an element of a list in Python? There are different ways to check if a string is an element of a list.
  1. in operator
  2. list.count() method
  3. list.index() method
To check if a string is part of any element in the list, use the any() function and list comprehensions. # check if string is part of any element myList = ['myHouse', 'myCar', 'myBoat'] any('House' in str for str in myList) House is present in the list, True is returned. True

Option 1: in operator

To check if a string is in a list, use the in operator on the list. # check if string is in a list using in operator myList = ['a', 'b', 'c'] if 'a' in myList: True The letter a is in myList, True is returned. True

Option 2: list.count() method

The list.count() method returns how often a string is in a list. If the returned number is over 0, we know the string is at least once in the list. # check if string is in a list using list.count() method myList = ['a', 'b', 'c'] if myList.count('a') > 0: True The letter a is once in myList. The count is higher than 0, therefore True is returned. True

Option 3: list.index() method

The third option is similar to the second option. The difference is that we need to take care of exception handling, because if the index is not found an ValueError exception is raised. ValueError: 'z' is not in list To take care of it wrap the code into a try/except block. # check if string is in a list using list.index() method myList = ['a', 'b', 'c'] try: if myList.index('a'): pass except: # ValueError exception means string is not in list False else: # No exception means string is in list True The letter a is in the list of letters. Because no exception is raised, the else block is executed and True is returned. True

                
        

Summary


Click to jump to section