Python - Find Index Containing String in List


Sometimes working with Python string, we may come across a real-world scenario where it can be useful for text parsing, pattern matching, and extracting specific information from text data. In Python, we have some built-in functions such as type(), index(), append(), and, isinstance() will be used to find the index containing String in List.

Let’s take an example of this:

The given input string,

my_list = [108, 'Safari', 'Skybags', 20, 60, 'Aristocrat', 78, 'Raj']

Output

1, 2, 5, 7

Explanation

The variable name my_list stores the input list that contains the mixing of integer and string in the list. The final output becomes the index position of the string present in the list.

Syntax

The following syntax is used in the examples

type()

The built-in function type() is used to return the type of the object. For example- a variable contains the value 4 and the type is integer.

index()

The index() is a built-in function in Python that can be used to search the element from the list and return the position of the element.

append() 

The append() is a built-in method in Python that accepts single element as a parameter to add at the end of the list.

isintance()

The built-in function isinstance() is used to check the object or variable belongs to specified class or data type.

Using for loop and index() function

In the following example, begin the program by storing the input list in the variable Fruit_list and displaying the list. Then iterate the list using for loop through variable i. Next, set the type of list to a string which will find the string element from the list. Finally, display the result by using the built-in function index() with a variable named Fruit_list.

Example

Fruit_list = ['Banana', 'Apple', 1000, 'Mango']
print("String present in the index:\n")
# iterate through the list of elements
for i in Fruit_list:
# check for type is str
    if type(i) is str:
# display index
        print(Fruit_list.index(i))

Output

String present in the index:

0
1
3

Specific string search to find the index

In the following example, we will start the program by defining the function named all_index() that accepts two parameters- value( receive the specified string) and qlist( receive the list item). The function uses a while loop to repeatedly call the index method of the list to find the next occurrence of value in the list. If an occurrence is found, its index is appended to the list ids. If no more occurrences are found, a ValueError is raised and caught, and the loop is exited. Finally, the list of indices is returned.The program uses the recursive function to set the input list and with the help of index() and append() it will find all indexes of the same string.

Example

def all_index(value, qlist):
    ids = []
    idx = -1
    while True:
        try:
            idx = qlist.index(value, idx+1)
            ids.append(idx)
        except ValueError:
            break
    return ids
print("Specific search on string index:")
all_index("Obm", ["Obm","Abc","Obm","Abm","Obm"])

Output

Specific search on string index:
[0, 2, 4]

Using index() function

In the following example, start the program by storing the input list in the variable list_1. Then use the print function to set the printing statement. Next, it will use the built-in function index that accepts the parameter as ‘POP’ with list_1 to find the specific index string.

Example

list_1 = ['PUSH', 'TOP','POP']
print("The following index is:")
list_1.index('POP')

Output

The following index is:
2

Using isinstance() function

In the following example, start the program by creating the list and storing it in the variable list1, and displaying the list. Then initialize the variable inx to 0 which will indicate the first element from the list and helps to iterate in the while loop. Using a while loop it will check the condition based on list index. It then uses the built-in function isinstance() that accepts the parameter- list[inx] and str to find the object type to return the specified string indexes.

Example

# create the list containing both string and integer
list1 = ['Vivek', 198, 200, 'Jayant', 'deep', 78]
# display list1
print("The original list:", list1)
# initialize index variable
inx = 0
# iterate through the list of elements using a while loop
print("The following string index:")
while inx < len(list1):
# check for type is str
    if isinstance(list1[inx], str):
# display the index
        print(inx)
# increment the index
    inx += 1

Output

The original list: ['Vivek', 198, 200, 'Jayant', 'deep', 78]
The following string index:
0
3
4

Conclusion

We discussed the various ways to solve the problem statement. The loops like for and while are helpful for iteration in the list and find the specific index using conditions. The built-in function index() returns the specific position of the string in the list and adds the filter string using append ().

Updated on: 16-Aug-2023

650 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements