Python if exist in array

Python : How to Check if an item exists in list ? | Search by Value or Condition

In this article we will discuss different ways to check if a given element exists in list or not.

Table of Contents

Introduction

Suppose we have a list of strings i.e.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from']

Now let’s check if given list contains a string element ‘at’ ,

Check if element exists in list using python “in” Operator

Condition to check if element is in List :

Читайте также:  Font awesome and css

It will return True, if element exists in list else return false.

Frequently Asked:

For example check if ‘at’ exists in list i.e.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # check if element exist in list using 'in' if 'at' in listOfStrings : print("Yes, 'at' found in List : " , listOfStrings)

Condition to check if element is not in List :

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # check if element NOT exist in list using 'in' if 'time' not in listOfStrings : print("Yes, 'time' NOT found in List : " , listOfStrings)

Check if element exist in list using list.count() function

count(element) function returns the occurrence count of given element in the list. If its greater than 0, it means given element exists in list.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # check if element exist in list using count() function if listOfStrings.count('at') > 0 : print("Yes, 'at' found in List : " , listOfStrings)

Check if element exist in list based on custom logic

Python any() function checks if any Element of given Iterable is True.

Let’s use it to check if any string element in list is of length 5 i.e.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # Check if element exist in list based on custom logic # Check if any string with length 5 exist in List result = any(len(elem) == 5 for elem in listOfStrings) if result: print("Yes, string element with size 5 found")

Instead of condition we can use separate function in any to match the condition i.e.

# List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] def checkIfMatch(elem): if len(elem) == 5: return True; else : return False; # Check if any string that satisfies the condition # in checkIfMatch() function exist in List result = any(checkIfMatch for elem in listOfStrings)

Complete example is as follows,

def checkIfMatch(elem): if len(elem) == 5: return True; else : return False; # List of string listOfStrings = ['Hi' , 'hello', 'at', 'this', 'there', 'from'] # Print the List print(listOfStrings) ''' check if element exist in list using 'in' ''' if 'at' in listOfStrings : print("Yes, 'at' found in List : " , listOfStrings) ''' check if element NOT exist in list using 'in' ''' if 'time' not in listOfStrings : print("Yes, 'time' NOT found in List : " , listOfStrings) ''' check if element exist in list using count() function ''' if listOfStrings.count('at') > 0 : print("Yes, 'at' found in List : " , listOfStrings) ''' check if element exist in list based on custom logic Check if any string with length 5 exist in List ''' result = any(len(elem) == 5 for elem in listOfStrings) if result: print("Yes, string element with size 5 found") ''' Check if any string that satisfies the condition in checkIfMatch() function exist in List ''' result = any(checkIfMatch for elem in listOfStrings) if result: print("Yes, string element with size 5 found")
['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'at' found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'time' NOT found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, 'at' found in List : ['Hi', 'hello', 'at', 'this', 'there', 'from'] Yes, string element with size 5 found Yes, string element with size 5 found

Источник

Python: Check if Array/List Contains Element/Value

In this tutorial, we’ll take a look at how to check if a list contains an element or value in Python. We’ll use a list of strings, containing a few animals:

animals = ['Dog', 'Cat', 'Bird', 'Fish'] 

Check if List Contains Element With for Loop

A simple and rudimentary method to check if a list contains an element is looping through it, and checking if the item we’re on matches the one we’re looking for. Let’s use a for loop for this:

for animal in animals: if animal == 'Bird': print('Chirp!') 

Check if List Contains Element With in Operator

Now, a more succinct approach would be to use the built-in in operator, but with the if statement instead of the for statement. When paired with if , it returns True if an element exists in a sequence or not. The syntax of the in operator looks like this:

Making use of this operator, we can shorten our previous code into a single statement:

if 'Bird' in animals: print('Chirp') 

This code fragment will output the following:

This approach has the same efficiency as the for loop, since the in operator, used like this, calls the list.__contains__ function, which inherently loops through the list — though, it’s much more readable.

Check if List Contains Element With not in Operator

By contrast, we can use the not in operator, which is the logical opposite of the in operator. It returns True if the element is not present in a sequence.

Let’s rewrite the previous code example to utilize the not in operator:

if 'Bird' not in animals: print('Chirp') 

Running this code won’t produce anything, since the Bird is present in our list.

But if we try it out with a Wolf :

if 'Wolf' not in animals: print('Howl') 

Check if List Contains Element With Lambda

Another way you can check if an element is present is to filter out everything other than that element, just like sifting through sand and checking if there are any shells left in the end. The built-in filter() method accepts a lambda function and a list as its arguments. We can use a lambda function here to check for our ‘Bird’ string in the animals list.

Then, we wrap the results in a list() since the filter() method returns a filter object, not the results. If we pack the filter object in a list, it’ll contain the elements left after filtering:

retrieved_elements = list(filter(lambda x: 'Bird' in x, animals)) print(retrieved_elements) 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Now, this approach isn’t the most efficient. It’s fairly slower than the previous three approaches we’ve used. The filter() method itself is equivalent to the generator function:

(item for item in iterable if function(item)) 

The slowed down performance of this code, amongst other things, comes from the fact that we’re converting the results into a list in the end, as well as executing a function on the item on each iteration.

Check if List Contains Element Using any()

Another great built-in approach is to use the any() function, which is just a helper function that checks if there are any (at least 1) instances of an element in a list. It returns True or False based on the presence or lack thereof of an element:

if any(element in 'Bird' for element in animals): print('Chirp') 

Since this results in True , our print() statement is called:

This approach is also an efficient way to check for the presence of an element. It’s as efficient as the first three.

Check if List Contains Element Using count()

Finally, we can use the count() function to check if an element is present or not:

This function returns the occurrence of the given element in a sequence. If it’s greater than 0, we can be assured a given item is in the list.

Let’s check the results of the count() function:

if animals.count('Bird') > 0: print("Chirp") 

The count() function inherently loops the list to check for the number of occurrences, and this code results in:

Conclusion

In this tutorial, we’ve gone over several ways to check if an element is present in a list or not. We’ve used the for loop, in and not in operators, as well as the filter() , any() and count() methods.

Источник

Python: check if item or value exists in list or array

Sometimes we need to know if an element or value is within a list or array in Python.

There may be a need to simply know if it exists, but it is also possible that we need to obtain the position of an element, that is, its index.

Today we will see how to do it in Python, to check if an element exists in array, as well as to obtain the index of a certain value.

Check if the element exists

We use the operator in , which returns a Boolean indicating the existence of the value within the array. This way:

As we can see, it does not matter if our array or list is string or integer type. Of course, they must be primitive data.

Obtain element index

If we want to obtain the index or position, we use the index method of the lists. This way:

When we run it, it prints position 1 (remember that the values in the list start at 0). It is important to remember that an error will be generated if the element does not exist in the list. To handle it, we can do something like this:

In that case, an exception is generated; because the element does not exist in the list.

I am available for hiring if you need help! I can help you with your project or homework feel free to contact me.
If you liked the post, show your appreciation by sharing it, or making a donation

Источник

Как проверить, есть ли элемент в списке

В Python списки играют роль контейнеров, которые могут хранить любые типы данных в виде коллекции. В 32-битной системе список может содержать до 536 870 912 элементов. Поэтому иногда бывает трудно определить, есть ли определенный элемент в списке.

Проверка наличия элемента в списке является одной из основных операций со списком в Python. Не удивительно, что подобные проверки можно осуществлять разными способами. В этой статье мы рассмотрим некоторые из них.

От редакции Pythonist: если хотите побольше узнать о списках, почитайте статью «Списки в Python: полное руководство для начинающих».

Проверяем, есть ли элемент в списке, при помощи оператора in

Самый удобный способ проверить, содержит ли список определенный элемент, — это воспользоваться оператором in . Этот оператор возвращает True, если элемент есть, и False, если его нет. При этом список не сортируется.

В приведенном ниже примере показано, как применяется оператор in в условном блоке:

name_list = ["Adam", "Dean", "Harvey", "Mick", "John"] if "John" in name_list: print("'John' is found in the list") else: print("'John' is not found in the list") if 'Ned' in name_list: print("'Ned' is found in the list") else: print("'Ned' is not found in the list") # Результат: # 'John' is found in the list # 'Ned' is not found in the list

От редакции Pythonist: об операторе in , его паре not in и прочих операторах можно почитать в статье «Операторы в Python».

Использование цикла for для проверки наличия элемента в списке

Проверить, есть ли элемент в списке, можно и при помощи цикла. Этот способ также довольно прост. Цикл будет по очереди сопоставлять каждый элемент списка с искомым элементом и остановится только в случае совпадения или полного отсутствия совпадения. Пример:

name_list = ["Adam", "Dean", "Harvey", "Mick", "John"] for name in name_list: if name == 'Adam': print("Found the element") # Результат: # Found the element

Как проверить, есть ли элемент в списке, при помощи функции any()

Встроенная функция any() проверяет, оценивается ли хоть один элемент в последовательности как True.

С помощью этой функции мы можем проверить, есть ли в строке подстрока, совпадающая с каким-нибудь элементом списка.

Приведенный ниже пример показывает, как работает функция any() . Мы проверяем, содержит ли строка «Adam lives in New York» какое-нибудь из имен, хранящихся в списке из первой строки.

name_list = ["Adam", "Dean", "Harvey", "Mick", "John"] string = "Adam lives in New York" print("The original list is: " + str(name_list)) print("The original string is: " + string) result = any(item in string for item in name_list) print("Does the string contain any name from the list: " + str(result)) # Результат: # The original list is: ['Adam', 'Dean', 'Harvey', 'Mick', 'John'] # The original string is: Adam lives in New York # Does the string contain any name from the list: True

Проверяем наличие элемента в списке при помощи метода count()

Встроенный метод count() возвращает количество вхождений указанного элемента в списке. Если элемента в списке нет, то count() вернет 0. Если возвращается целое положительное число больше 0, это означает, что список содержит элемент.

name_list = ["Adam", "Dean", "Harvey", "Mick", "John"] result = name_list.count("Harvey") if result > 0: print("Harvey exists in the list") else: print("Harvey does not exist in the list") # Результат: # Harvey exists in the list

Итоги

В этой статье мы рассмотрели на примерах, как проверить, есть ли элемент в списке. Для проверок мы использовали оператор in , цикл for , методы any() и count() .

Источник

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