Python – Find Index containing String in List
In this article, we will explore how to find the index of a string in a list in Python. It involves identifying the position where a specific string appears within the list.
Using index()
index()
method in Python is used to find the position of a specific string in a list. It returns the index of the first occurrence of the string, raising it ValueError
if the string is not found.
Example:
a = ['sravan', 98, 'harsha', 'jyothika',
'deepika', 78, 90, 'ramya']
b= 'jyothika'
res = a.index(b)
print(res)
Output
3
Note: If the string isn’t found, ValueError will be raised. Handle it using a try-except block:
try:
index = a.index('jyothika')
except ValueError:
index = -1 # Or any default value
Let’s explore more methods to find the index of a string in a list.
Table of Content
Using next()
next()
method, combined with a generator expression, can be used to find the index of a string in a list. It returns the first match and stops further searching, offering a compact and efficient solution.
Example:
a = ['sravan', 98, 'harsha', 'jyothika',
'deepika', 78, 90, 'ramya']
# Use a generator expression with the
#`next` function to find the index
res = next((i for i, value in enumerate(a) if value == 'jyothika'), -1)
print(res)
Output
3
Explantion:
- This code uses
next()
with a generator expression to search for'jyothika'
in the lista
. - If found, it returns the index; if not, it returns
-1
.
Using for Loop
This method manually iterates through the list, comparing each element with the target string. It returns the index of the first match, providing full control over the iteration process.
a = ['sravan', 98, 'harsha', 'jyothika',
'deepika', 78, 90, 'ramya']
# loop to find the index
for i in range(len(a)):
if a[i] == 'jyothika':
print(i)
break
else:
print("Not found")
Output
3
Using List Comprehension
List comprehension finds all indices of a string in a list, making it ideal for multiple occurrences but inefficient for just the first match.
Example:
a = ['sravan', 98, 'harsha', 'jyothika',
'deepika', 78, 90, 'ramya']
# find all indices
indexes = [i for i, value in enumerate(a) if value == 'jyothika']
print(indexes[0] if indexes else -1)
Output
3
Explanation:
- This code uses list comprehension to find all indices of
'jyothika'
in the lista
. - It prints the first index if found, otherwise returns
-1
if no match is found.