Built with Tutify.io

    AIStudyLabs

    Python List Contains - Check if Element Exists in List

    Python List Contains - Check if Element Exists in List

    How to check if an element contains/exists in a list in python? To check if an element or item exists in a list you can simply use the in operator. If an element exists the expression returns True, otherwise, returns False. Besides this, there are other functions that can be used to check.

    Methods to Check if Element Contains in Python List:

    1. Python in operator to check if an element contains in a list.
    2. User count() and Counter().
    3. Use List comprehension,
    4. filter() with any() method.
    5. index() - returns an index if the element exists, use this to check if the element exists. if the element is not present, ValueError is raised.

    <a id="h-1-quick-examples-of-list-contains"></a>

    1. Quick Examples of List Contains

    If you are in a hurry, below are some quick examples of how to check whether the element is present in the list or not.

    
    # Quick Examples to check if element contains in list
    
    # Example 1: Consider list of integers
    marks=[90,56,78,90,45]
    print("Actual List: ",marks)
    
    # Example 2: Using if statement
    if 78 in marks:
    	print("Exist!")
    else:
    	print("Not exist!")
     
    # Example 3: Using count()
    if(marks.count(78)>0):
    	print("Exist!")
    else:
    	print("Not exist!")
     
    # Example 4: Using Counter()
    from collections import Counter
    if(Counter(marks)[78]>0):
    	print("Exist!")
    else:
    	print("Not exist!")
     
    # Example 5: Using index() with try-except block
    try:
       marks.index(78)
       print("Exist!")
    except:
        print("Not exist!")
    
    # Example 6: Using any()
    print(any(i==99 for i in marks))
    
    # Example 7: Using any() with filter()
    print(any(list(filter(lambda x: x==30, marks))))
    
    # Example 8: Using any() with List Comprehension
    print(any(i for i in marks if i == my_element))
    

    <a id="h-2-check-if-python-list-contains-element-using-in-operator"></a>

    2. Check if Python List Contains Element using in Operator

    By using the in operator you can check if the element contains in the list in python. The in is the most convenient way to check whether an item exists on the list and you can use not in operator to check if the element does not exist in the list. With the in operator, if an element exists, it returns True otherwise returns False. Here, is the syntax of using an in operator with the list.

    
    # Syntax
    element in mylist
    

    Here, the element is the value you wanted to check if it contains in the list. and mylist is the list object where you wanted to check for element existence.

    
    # Check if element exists in list
    marks=[90,56,78,90,45]
    print(78 in marks) # Output: True
    print(79 in marks) # Output: False
    

    3. Use in Operator with if Statement

    In real-time, you would use the in operator to check whether an element exists in Python List along with the if statement.

    <a id="h-3-1-if-statement-syntax"></a>

    3.1 if statement Syntax

    Syntax of the if condition that uses an in operator.

    
    # Using if statement
    if my_element in mylist1:
    	print("Exist!")
    else:
            print("Not exist!")
    

    Here,

    <a id="h-3-2-if-statement-example"></a>

    3.2 if statement Example

    Let's have a list with some integers and check whether the element 78 exists in the list or not.

    
    # Consider list of integers
    marks=[90,56,78,90,45]
    print("Actual list:",marks)
    
    # Check if an element exists in the list
    my_element=78
    
    # Using if statement
    if my_element in marks:
    	print(f"{my_element} Exist!")
    else:
    	print(f"{my_element} Not exist!")
    

    Yields below output.

    The example print Exists! as element value 78 contains in the list (if block is executed).

    <a id="h-4-use-count-to-check-if-python-list-contains-element"></a>

    4. Use count() to Check if Python List Contains Element

    The count()method will show the number of times it occurs in the entire list, in other words count() method is used to return the total occurrences of the given element from the list, if the occurrence count of our specified element is greater than 0, we can say that our element exists in the list.

    <a id="h-4-1-count-syntax"></a>

    4.1 count() Syntax

    The syntax for the count(). Here, mylist1 is the input list and my_element is the element which you wanted to check if it exists or contains in the python list named mylist1.

    
    # Using count()
    if(mylist1.count(my_element)>0):
    	  print("Exist!")
    else:
    	print("Not exist!")
    

    <a id="h-4-2-count-example"></a>

    4.2 count() Example

    Let's have a list with some strings and check whether "japan" exists in the list or not using the count() method.

    
    # Consider list of strings
    countries=["india","japan","china","russia","france"]
    
    my_element="japan"
    
    # Using count()
    if(countries.count(my_element)>0):
    	  print("Exist!")
    else:
    	print("Not exist!")
     
    # Output:
    # Exist!
    

    As the "japan" exists in the list, if block is executed and prints the Exist! to console.

    <a id="h-5-use-counter-to-check-if-list-contains-element"></a>

    5. Use Counter() to Check if List Contains Element

    The counter() is similar to the count() method, the counter holds the data in an unordered collection which allows us to count the items in an iterable list. It is important to import counter from the collections module. Let's use this to check if an element contains in a python list.

    <a id="h-5-1-counter-syntax"></a>

    5.1 Counter() Syntax

    The syntax of the counter().

    
    # Syntax & usage of counter()
    if(Counter(mylist1)[my_element]>0):
    	print("Exist!")
    else:
    	print("Not exist!")
    

    <a id="h-5-2-counter-example-with-python-list-contains"></a>

    5.2 counter() Example with Python List Contains

    Let's have a list with some strings and check whether some elements exist in this list or not using the counter() method.

    
    from collections import Counter
    # Consider list of strings
    countries=["india","japan","china","russia","france"]
    
    my_element="russia"
    
    # Using Counter()
    if(Counter(countries)[my_element]>0):
    	  print("Exist!")
    else:
    	print("Not exist!")
     
    my_element="USA"
     # Using Counter()
    if(Counter(countries)[my_element]>0):
    	  print("Exist!")
    else:
    	print("Not exist!")
     
    # Output:
    # Exist!
    # Not exist!
    

    Here, "russia" exists in the list hence, if block is executed and "USA" doesn't exist in the list hence else block is executed.

    <a id="h-6-using-index-to-check-list-exists-or-not"></a>

    6. Using index() to Check List Exists or Not

    The Python list index() method will return the index position of an element by taking the element as a parameter, if the element exists, it will return the index, otherwise, ValueError is raised. To handle this error, we have to use the try-except block and use this method inside the try block. We can specify error messages in the except block.

    <a id="h-6-1-index-syntax"></a>

    6.1 index() Syntax

    The syntax for the list index() method.

    
    # Using index() with try-except block
    try:
       mylist1.index(my_element)
       print("Exist!")
    except:
        print("Not exist!")
    

    <a id="h-6-2-list-contains-example-using-index"></a>

    6.2 List Contains Example using index

    Let's have a list with some strings and check whether some elements exist in this list or not using the index() method.

    Here, item 12 exists in the list so no exception is raised from the try block and item 800 doesn't exist in the list so an error is raised, and the catch block is executed.

    
    # Consider list of integers
    marks=[12,43,56,78,54,33,22]
    
    # Using index() with try-except block
    try:
       marks.index(12)
       print("Exist!")
    except:
        print("Not exist!")
    
    # Using index() with try-except block
    try:
       marks.index(800)
       print("Exist!")
    except:
        print("Not exist!")
    
    # Output:
    # Exist!
    # Not exist!
    

    <a id="h-7-using-any-to-check-list-contains-element"></a>

    7. Using any() to Check List Contains Element

    7.1 any() with for loop

    The any() function in python can be used to check if the element contains in a list. we will check if our element is equal to any one of the elements in the list or not using this method by iterating the list using for loop.

    1. If at least one element matches with an element, True is returned.
    2. If no element is matched, False is returned.

    Example: Let's have a list with some integers and check whether some elements exist in this list or not by passing for loop to iterate all elements and == operator to check each element.

    
    # Consider list of integers
    marks=[12,43,56,78,54,33,22]
    
    # using any()
    print(any(i==12 for i in marks))
    print(any(i==45 for i in marks))
    
    # Output:
    # True
    # False
    

    Explanation:

    7.2 any() with filter()

    Inside this method, we can pass a lambda expression as the first parameter for specifying the condition and the second parameter as the input list. The operator used inside the expression is == (Equal to) operator. So all the matched elements are filtered and stored in a list. If the list contains at least one element, any() will return True. Otherwise False is returned.

    Example: Let's have a list with some integers and check whether some elements exist in this list or not by passing the filter() function.

    
    # Consider list of integers
    marks=[12,43,56,78,54,33,22]
    
    # Using any() with filter()
    print(any(list(filter(lambda x: x==30, marks))))
    print(any(list(filter(lambda x: x==22, marks))))
    
    # Output:
    # False
    # True
    

    Explanation:

    7.3 any() with List comprehension

    We will pass list comprehension inside any() method. First, we will iterate the list and check if the iterator is equal to our element or not using the if condition. If exists, it is stored in a list, otherwise, it will be ignored, If the list contains at least one element, any() will return True, otherwise False is returned.

    Example: Let's have a list with some integers and check whether some elements exist in this list or not by passing list comprehension.

    
    # Consider list of integers
    marks=[12,43,56,78,54,33,22]
    
    # Using any() with List Comprehension
    print(any(i for i in marks if i == 12))
    print(any(i for i in marks if i == 60))
    
    # Output:
    # True
    # False
    

    Explanation:

    <a id="h-frequently-asked-questions-on-python-list-contains"></a>

    Frequently Asked Questions on Python List Contains

    You can use the in operator to check if an element is present in a list. For example, element_to_check in my_list returns True if element_to_check is found in my_list, and False otherwise. You can replace element_to_check with the value you want to check for in the list.

    The in operator in Python returns a Boolean value. It evaluates to True if the specified element is found in the sequence (such as a list, tuple, string, or set), and False otherwise.

    You can check if any element in a list satisfies a condition using the any() function along with a generator expression or a list comprehension.

    You can count the occurrences of an element in a list using the count() method. For example, the count() method is called on the list my_list with the argument element_to_count, and it returns the number of occurrences of that element in the list.

    The in operator is case-sensitive. For example, if you have a list of strings, it will distinguish between uppercase and lowercase characters.

    You can find the index of an element in a list using the index() method. For example, the index() method is used to find the index of element_to_find in the list my_list. If the element is found, it returns the index; otherwise, it raises a ValueError. To handle this, a try and except block is used.

    <a id="h-conclusion"></a>

    Conclusion

    In this article, you have learned how to check if the element contains in the list in python by using in operator, which checks if an element exists in the list or not. if it exists it returns True otherwise, returns False. Besides this, you can also use the count(), counter(), index, and any. When you use the index, it returns an error if the element is not found hence, it's good practice to use try-except.

    <a id="h-related-articles"></a>

    Related Articles

    References