How to find strings in a list python

In this article, we’ll take a look at how we can find a string in a list in Python.

There are various approaches to this problem, from the ease of use to efficiency.

Using the ‘in’ operator

We can use Python’s in operator to find a string in a list in Python. This takes in two operands a and b, and is of the form:

Here, ret_value is a boolean, which evaluates to True if a lies inside b, and False otherwise.

We can directly use this operator in the following way:

a = [1, 2, 3]

b = 4

if b in a:
    print['4 is present!']
else:
    print['4 is not present']

Output

We can also convert this into a function, for ease of use.

def check_if_exists[x, ls]:
    if x in ls:
        print[str[x] + ' is inside the list']
    else:
        print[str[x] + ' is not present in the list']


ls = [1, 2, 3, 4, 'Hello', 'from', 'AskPython']

check_if_exists[2, ls]
check_if_exists['Hello', ls]
check_if_exists['Hi', ls]

Output

2 is inside the list
Hello is inside the list
Hi is not present in the list

This is the most commonly used, and recommended way to search for a string in a list. But, for illustration, we’ll show you other methods as well.

Using List Comprehension

Let’s take another case, where you wish to only check if the string is a part of another word on the list and return all such words where your word is a sub-string of the list item.

Consider the list below:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

If you want to search for the substring Hello in all elements of the list, we can use list comprehensions in the following format:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

matches = [match for match in ls if "Hello" in match]

print[matches]

This is equivalent to the below code, which simply has two loops and checks for the condition.

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

matches = []

for match in ls:
    if "Hello" in match:
        matches.append[match]

print[matches]

In both cases, the output will be:

['Hello from AskPython', 'Hello', 'Hello boy!']

As you can observe, in the output, all the matches contain the string Hello as a part of the string. Simple, isn’t it?

Using the ‘any[]’ method

In case you want to check for the existence of the input string in any item of the list, We can use the any[] method to check if this holds.

For example, if you wish to test whether ‘AskPython’ is a part of any of the items of the list, we can do the following:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

if any["AskPython" in word for word in ls]:
    print['\'AskPython\' is there inside the list!']
else:
    print['\'AskPython\' is not there inside the list']

Output

'AskPython' is there inside the list!

Using filter and lambdas

We can also use the filter[] method on a lambda function, which is a simple function that is only defined on that particular line. Think of lambda as a mini function, that cannot be reused after the call.

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

# The second parameter is the input iterable
# The filter[] applies the lambda to the iterable
# and only returns all matches where the lambda evaluates
# to true
filter_object = filter[lambda a: 'AskPython' in a, ls]

# Convert the filter object to list
print[list[filter_object]]

Output

We do have what we expected! Only one string matched with our filter function, and that’s indeed what we get!

Conclusion

In this article, we learned about how we can find a string with an input list with different approaches. Hope this helped you with your problem!

References

  • JournalDev article on finding a string in a List
  • StackOverflow question on finding a string inside a List

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']

Output:

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'{s} is present in the list']
else:
    print[f'{s} is not present in the list']

Output:

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'{s} is present in the list for {count} 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'{s} is present in {l1} at indexes {matched_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.

How do you find where a string is in a list Python?

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.

How do you check if a list contains a string Python?

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list. count[] function.

How do you extract a string from a list in Python?

Here, we extract a number from the list string, we have used the split[] method to extract the numbers. split[] is a predefined method in python which cuts the specified character and returns other characters in the list.

How do I find a specific element in a list Python?

To find an element in the list, use the Python list index[] method, The index[] is an inbuilt Python method that searches for an item in the list and returns its index. The index[] method finds the given element in the list and returns its position.

Chủ Đề