Python – Find Index containing String in List
Given a list, the task is to write a Python Program to find the Index containing String.
Example:
Input: [‘sravan’, 98, ‘harsha’, ‘jyothika’, ‘deepika’, 78, 90, ‘ramya’]
Output: 0 2 3 4 7
Explanation: Index 0 2 3 4 7 contains only string.
Method 1: Using type() operator in for loop
By using type() operator we can get the string elements indexes from the list, string elements will come under str() type, so we iterate through the entire list with for loop and return the index which is of type string.
Python3
# create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya']# displaylist1# iterate through list of elementsfor i in list1: # check for type is str if(type(i) is str): # display index print(list1.index(i)) |
Output:
0 2 3 4 7
Method 2: Using type() operator in List Comprehension
By using list comprehension we can get indices of string elements.
Syntax: [list.index(iterator) for iterator in list if(type(iterator) is str)]
Python3
# create a list of names and markslist1 = ['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya']# displaylist1# list comprehensionprint([list1.index(i) for i in list1 if(type(i) is str)])# list comprehension display stringsprint([i for i in list1 if(type(i) is str)]) |
Output:
[0, 2, 3, 4, 7] ['sravan', 'harsha', 'jyothika', 'deepika', 'ramya']



