Python check if string is in array

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:

Читайте также:  Php вызов public функции

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 Find String in List

Python Find String in List

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

We can use Python in operator to check if a string is present in the list or not. There is also a not in operator to check if a string is not present in the list.

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] # string in the list if 'A' in l1: print('A is present in the list') # string not in the list if 'X' not in l1: print('X is not present in the list') 
A is present in the list X is not present in the list 

Recommended Reading: Python f-strings Let’s look at another example where we will ask the user to enter the string to check in the list.

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = input('Please enter a character A-Z:\n') if s in l1: print(f' is present in the list') else: print(f' is not present in the list') 
Please enter a character A-Z: A A is present in the list 

Python Find String in List using count()

We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list.

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.count(s) if count > 0: print(f' is present in the list for times.') 

Finding all indexes of a string in the list

There is no built-in function to get the list of all the indexes of a string in the list. Here is a simple program to get the list of all the indexes where the string is present in the list.

l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' matched_indexes = [] i = 0 length = len(l1) while i < length: if s == l1[i]: matched_indexes.append(i) i += 1 print(f'is present in at indexes ') 

Output: A is present in ['A', 'B', 'C', 'D', 'A', 'A', 'C'] at indexes [0, 4, 5] You can checkout complete python script and more Python examples from our GitHub Repository.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Python Check if List Contains a String

Python Check if List Contains a String

  1. Use the for Loop to Check a Specific String in a Python List
  2. Use the List Comprehension to Check a Specific String in a Python List
  3. Use the filter() Function to Get a Specific String in a Python List

Strings are a sequence of characters. Just like strings store characters at specific positions, we can use lists to store a collection of strings.

In this tutorial, we will get a string with specific values in a Python list.

Use the for Loop to Check a Specific String in a Python List

The for is used to iterate over a sequence in Python.

Its implementation for obtaining a string containing specific values is shown in the example below.

py_list = ['a-1','b-2','c-3','a-4'] new_list =[] for x in py_list:  if "a" in x:  new_list.append(x) print(new_list) 

In the above code, the if statement is used inside the for loop to search for strings containing a in the list py_list . Another list named new_list is created to store those specific strings.

Use the List Comprehension to Check a Specific String in a Python List

List comprehension is a way to create new lists based on the existing list. It offers a shorter syntax being more compact and faster than the other functions and loops used for creating a list.

py_list = ['a-1','b-2','c-3','a-4'] r = [s for s in py_list if "a" in s] print(r) 

In the above code, list comprehension is used to search for strings having a in the list py_list .

Note that writing the same code using other functions or loops would have taken more time, as more code is required for their implementation, but list comprehension solves that problem.

We can also use list comprehension to find out strings containing multiple specific values i.e., we can find strings containing a and b in py_list by combining the two comprehensions.

py_list = ['a-1','b-2','c-3','a-4','b-8'] q = ['a','b'] r = [s for s in py_list if any(xs in s for xs in q)] print(r) 

Use the filter() Function to Get a Specific String in a Python List

The filter() function filters the given iterable with the help of a function that checks whether each element satisfies some condition or not.

It returns an iterator that applies the check for each of the elements in the iterable.

py_lst = ['a-1','b-2','c-3','a-4'] filter(lambda x: 'a' in x,py_lst) print (filter(lambda x: 'a' in x,py_lst)) 

Note that the above output is a filter-iterator type object since the filter() function returns an iterator instead of a list.

We can use the list() function as shown in the code below to obtain a list.

list(filter(lambda x: 'a' in x,py_lst)) 

In the above code, we have used filter() to find a string with specific values in the list py_list .

Related Article - Python String

Related Article - Python List

Copyright © 2023. All right reserved

Источник

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