Python check if list contains value

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.

  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.

1. Quick Examples of List Contains

Following are 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 # Consider list of integers marks=[90,56,78,90,45] print("Actual List: ",marks) # Using if statement if 78 in marks: print("Exist!") else: print("Not exist!") # Using count() if(marks.count(78)>0): print("Exist!") else: print("Not exist!") # Using Counter() from collections import Counter if(Counter(marks)[78]>0): print("Exist!") else: print("Not exist!") # Using index() with try-except block try: marks.index(78) print("Exist!") except: print("Not exist!") # Using any() print(any(i==99 for i in marks)) # Using any() with filter() print(any(list(filter(lambda x: x==30, marks)))) # Using any() with List Comprehension print(any(i for i in marks if i == my_element)) 

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.

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.

Читайте также:  Scrollbar css что это

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!") 
  • If the element exists, the condition will become True and statements inside if block are executed.
  • If the element doesn’t exist, the condition will become False and statements inside the else block are executed.

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) my_element=78 # Using if statement if my_element in marks: print("Exist!") else: print("Not exist!") # Output: # Actual List: [90, 56, 78, 90, 45] # Exist! 

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

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.

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!") 

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.

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.

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!") 

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.

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.

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!") 

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.

Читайте также:  Как удалить css контент

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! 

7. Using any() to Check List Contains Element

7.1 any() with 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 
  • Element 12 exists in the list, so True is returned.
  • Element 45 doesn’t exist in the list, so False is returned.

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 
  • Element 30 doesn’t exist in the list, so False is returned.
  • Element 22 exists in the list, so True is returned.

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 
  • Element 12 contains in the list, so True is returned.
  • Element 60 doesn’t exist in the list, so False is returned.

8. 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.

References

You may also like reading:

Источник

Python list contains: How to check if an item exists in list?

In Python, lists are important containers as they store all kinds of data types as a collection. It can contain up to 536,870,912 items in a 32-bit system. Sometimes it is difficult to know if the list contains a particular item. Python has various ways by which we can find out if the list contains the item.

Читайте также:  Python программирование искусственный интеллект

Table of contents

Python lists contain — Introduction

Checking if an element is present in a list is one of the basic list operations in Python and there are many different ways we can check that. In this tutorial, we will be covering some of the ways to check if the lists contain an element.

Check if the Python list contains an element using in operator

The most convenient way to check whether the list contains the element is using the in operator. Without sorting the list in any particular order, it returns TRUE if the element is there, otherwise FALSE.

The below example shows how this is done by using ‘in’ in the if-else statement.

Input:

list = [Adam, Dean, Harvey, Mick, John] if 'John' in list: print (" 'John' is found in the list") else print (" 'John' is not found in the list") if 'Ned' in list: print (" 'Ned' is found in the list") else print (" 'Ned' is not found in the list")

Output:

'John' is found in the list 'Ned' is not found in the list

Using for loop to check if the list contains an element in Python

Another simple method to check if the list contains the element is looping through it. As the name suggests, the loop will match each element of the list with the element that we are looking for one by one and will only stop if there’s a match or there is no match at all. The below example illustrates this.

Input:

list = [Adam, Dean, Harvey, Mick, John] for name in list: if name == 'Adam': print ("Found the element")

Output:

Using any() to check if the list contains

The function any() is a built-in approach that checks for a match in a string with a match of each list element.

The below example shows how the any() function works. We check if there are any common items in the string, ‘Adam lives in New York’, and the list mentioned in the first line.

Input:

list = [Adam, Dean, Harvey, Mick, John] string = "Adam lives in New York" print ("The original list is: " + str(list)) print ("The original string is: " + string) result = any(item in string for item in list) print ("Does the string contain 'Adam': " + str(result))

Output:

The original list is: [Adam, Dean, Harvey, Mick, John] The original string is: Adam lives in New York Does the string contain 'Adam': True 

count() to check if the list contains

Another built-in method in Python, count() returns the number of times the passed element occurs in the list. If the element is not there in the list then the count() will return 0. If it returns a positive integer greater than 0, it means the list contains the element.

Input:

list = [Adam, Dean, Harvey, Mick, John] result = list.count(Harvey) if result > 0: print("Harvey exists in the list") else: print("Harvey does not exist in the list")

Output:

Harvey exists in the list

Closing thoughts

In this tutorial, we have used the ‘in’ operator, for loop, any() and count() methods to check whether a particular item exists in the list or not. One can learn more about other concepts related to Python here.

Источник

Оцените статью