Open In App

Python program to find the String in a List

Last Updated : 12 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list, the task is to write a program that checks whether any element in the list with string data type is present in the list or not, by using the methods or ways provided in Python.

Examples:

Input: l=[1, 1.0, 'have', 'a', 'geeky', 'day']; s='geeky'
Output: True
Explanation: geeky is present in the input list

Find the String in a List in Python

Below are the methods that we will cover in this article:

Find the String in a List Using the ‘in’ Operator

The in operator comes in handy for checking whether a particular string/element exists in the list. So here is the code where we use a conditional statement with ‘in’ operator to check if we have the particular string in the list and the conditional operator returns boolean values according to it.

Python3




# assign list
l = [1, 2.0, 'have', 'a', 'geeky', 'day']
 
# assign string
s = 'geeky' 
 
# check if string is present in the list
if s in l:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


Output

geeky is present in the list

Time Complexity: O(n)
Auxiliary Space: O(1)

Find String in List using count() method

The count() function is used to count the occurrence of a particular string in the list. If the count of a string is more than 0 in Python list of strings, it means that a particular string exists in the list, else that string doesn’t exist in the list. In the given code we use the we use the conditional statement to check whether the particular string is present or not if it is not present the count function returns 0.

Python3




# assign list
l = ['1', 1.0, 32, 'a', 'geeky', 'day']
 
# assign string
s = 'prime'
 
# check if string is present in list
if l.count(s) > 0:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


Output

prime is not present in the list

Time Complexity: O(n)
Auxiliary Space: O(1)

Find a String in a List Using List Comprehension

List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. It is used to transform iterative statements into formulas. In this, we create a list to store the string which we have to find in the list and then store it in the new list, and then we can check whether the new list is empty.

Python3




# assign list
l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
 
# assign string
s = 'geek'
 
# list comprehension
compare = [i for i in l if s in l]
 
# check if string is present in list
if len(compare) > 0:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


Output

geek is present in the list

Time Complexity: O(n) 
Space Complexity: O(n)

Find the String in the List Using any() Function

The any() function is used to check the existence of an element in the list. it’s like- if any element in the string matches the input element, print that the element is present in the list, else, print that the element is not present in the list.

Python3




# assign list
l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
 
# assign string
s = 'prime'
 
# check if string is present in list
if any(s in i for i in l):
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


Output

prime is not present in the list

Time Complexity: O(n)
Space Complexity: O(n)

Find String in a List Using map() and find() Methods

Here with map() we convert every datatype of the list into a string and then join them and make a single string then with the help of find() function we search the string in it.

Python3




l = [1, 2.0, 'have', 'a', 'geeky', 'day']
# assign string
s = 'geeky'
nl=list(map(str,l))
x=" ".join(nl)
# check if string is present in the list
if x.find(s)!=-1:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


Output

geeky is present in the list

Time Complexity: O(n) 
Space Complexity: O(n)

Find the String in a List Using operator methods

Example 1: Using operator.countOf() method

In Python the operator module we have cout.Of() method which returns the number of occurrences of the particular element which presents in the list and if not present then returns 0 so through this we can also find the string in a list

Python3




import operator as op
# assign list
l = ['1','1', 1.0, 32, 'a', 'geeky', 'day']
 
# assign string
s = 'prime'
 
# check if string is present in list     
if op.countOf(l, s):
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')
 
#it return the number of occurence of element in the list
print('The no. of occurrence of "1" in the list is:',op.countOf(l,'8'))


Output

prime is not present in the list
The no. of occurrence of "1" in the list is: 0

Time Complexity: O(N)
Auxiliary Space : O(1)

Example 2: Using operator.contains()

Check whether the given string is present in the list using operator.contains(). If the yes display “string” is present in the  list else display “string” is not present in the list

Python3




# assign list
import operator
l = [1, 2.0, 'have', 'a', 'geeky', 'day']
# assign string
s = 'geeky'
# check if string is present in the list
if operator.contains(l, s):
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


Output

geeky is present in the list

Time Complexity : O(n) n – length of list
Auxiliary Space : O(1)

Find a String in a List Using try/except and index()

You can use the index() method to find the first index of a string in a list. If the string is present in the list, the index() method returns the first index of the string otherwise, it raises a ValueError. To check if a string is present in a list, you can wrap the index() method in a try-except block, and print a message indicating whether the string is present in the list or not.

Python3




# assign list
l = [1, 2.0, 'have', 'a', 'geeky', 'day']
  
# assign string
s = 'geeky'
  
try:
    # check if string is present in list
    index = l.index(s)
    print(f'{s} is present in the list at index {index}')
except ValueError:
    print(f'{s} is not present in the list')


Output

geeky is present in the list at index 4

Time Complexity: O(n)
Auxiliary Space: O(1), as the method uses only a few constant-sized variables, regardless of the size of the list.

Find the String in the List Using re module

Initialize a list l and a string s then import the re module. Use the re.search() function to search for the string s in the list l If a match is found, print that the string s is present in the list If no match is found, print that the string s is not present in the list.

Python3




import re
 
# assign list
l = [1, 2.0, 'have', 'a', 'geeky', 'day']
 
# assign string
s = 'geeky'
 
# check if string is present in each string in the list
for item in l:
    if isinstance(item, str) and re.search(s, item):
        print(f'{s} is present in the list')
        break
else:
    print(f'{s} is not present in the list')
# This code is contributed by Vinay Pinjala.


Output

geeky is present in the list

Time complexity: O(n*m),
Auxiliary Space: O(1)

Python List of Strings Finding Using enumerate() Function

In this example, the Python code uses enumerate to iterate through a mixed-type list, checking if the string ‘geeky’ is present in any string elements. The re.search() function is employed to perform a regex search within string elements, and the result is printed indicating the presence or absence of the string ‘geeky’ along with its index in the list.

Python3




import re
 
# Sample list of mixed types
l = [1, 2.0, 'have', 'a', 'geeky', 'day']
 
# Assign string
s = 'geeky'
 
# Check if string is present in each string in the list using enumerate
for index, item in enumerate(l):
    if isinstance(item, str) and re.search(s, item):
        print(f'{s} is present in the list at index {index}')
        break
else:
    print(f'{s} is not present in the list')


Output

geeky is present in the list at index 4

Time complexity: O(n)
Auxiliary Space: O(1)

Find the String in a List Using numpy library

Import the numpy module then initialize a list variable l with some string values. Initialize a string variable s with the value “prime”.Use a list comprehension to create a list of boolean values, where each value corresponds to whether the string s is present in the corresponding element of the list l.Use the np.any() method to check if any of the values in the resulting list is True. Print a message indicating whether the string s is present in the list or not, based on the value of res.

Python3




import numpy as np
 
# assign list
l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']
 
# assign string
s = 'prime'
 
# check if string is present in list
res = np.any([s in i for i in l])
 
if res:
    print(f'{s} is present in the list')
else:
    print(f'{s} is not present in the list')


Output

prime is not present in the list

Time complexity: O(nm)
Auxiliary Space: O(nm)



Previous Article
Next Article

Similar Reads

Python | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isdigit() This task can be performed using a combinat
6 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python Program to convert List of Integer to List of String
Given a List of Integers. The task is to convert them to a List of Strings. Examples: Input: [1, 12, 15, 21, 131]Output: ['1', '12', '15', '21', '131']Input: [0, 1, 11, 15, 58]Output: ['0', '1', '11', '15', '58']Method 1: Using map() [GFGTABS] Python3 # Python code to convert list of # string into sorted list of integer # List initialization list_i
5 min read
Python program to find the sum of Characters ascii values in String List
Given the string list, the task is to write a Python program to compute the summation value of each character's ASCII value. Examples: Input : test_list = ["geeksforgeeks", "teaches", "discipline"] Output : [133, 61, 100] Explanation : Positional character summed to get required values. Input : test_list = ["geeksforgeeks", "discipline"] Output : [
4 min read
Python | Convert list of tuples to list of list
This is a quite simple problem but can have a good amount of application due to certain constraints of Python language. Because tuples are immutable, they are not easy to process whereas lists are always a better option while processing. Let's discuss certain ways in which we can convert a list of tuples to list of list. Method #1: Using list compr
8 min read
Python | Convert a string representation of list into list
Many times, we come across the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to a list in Python to perform tasks is quite common in web development. Convert a string of a list in
6 min read
Python | Convert list of string into sorted list of integer
Given a list of string, write a Python program to convert it into sorted list of integer. Examples: Input: ['21', '1', '131', '12', '15'] Output: [1, 12, 15, 21, 131] Input: ['11', '1', '58', '15', '0'] Output: [0, 1, 11, 15, 58] Let's discuss different methods we can achieve this task. Method #1: Using map and sorted() C/C++ Code # Python code to
4 min read
Python | Convert list of numerical string to list of Integers
Many times, the data we handle might not be in the desired form for any application and has to go through the stage of preprocessing. One such kind of form can be a number in the form of a string that too is a list in the list and we need to segregate it into digit-separated integers. Let's discuss certain ways in Python in which this problem can b
6 min read
Python | Convert string enclosed list to list
Given a list enclosed within a string (or quotes), write a Python program to convert the given string to list type. Examples: Input : "[0, 2, 9, 4, 8]" Output : [0, 2, 9, 4, 8] Input : "['x', 'y', 'z']" Output : ['x', 'y', 'z'] Approach #1: Python eval() The eval() method parses the expression passed to this method and runs python expression (code)
5 min read
Python | Convert mixed data types tuple list to string list
Sometimes, while working with records, we can have a problem in which we need to perform type conversion of all records into a specific format to string. This kind of problem can occur in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + tuple() + str() + generator expression The co
5 min read