Python Find Index containing String in List (original) (raw)

Last Updated : 19 Dec, 2024

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:

Python `

a = ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya'] b= 'jyothika'

res = a.index(b) print(res)

`

**Note: If the string isn’t found, ValueError will be raised. Handle it using a try-except block:

Python `

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:

Python ``

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)

``

**Explantion:

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.

Python `

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")

`

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:

Python `

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)

`

**Explanation: