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.
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
list1 = [ 'sravan' , 98 , 'harsha' , 'jyothika' ,
'deepika' , 78 , 90 , 'ramya' ]
list1
for i in list1:
if ( type (i) is str ):
print (list1.index(i))
|
Time Complexity: O(n)
Auxiliary Space: O(1)
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
list1 = [ 'sravan' , 98 , 'harsha' , 'jyothika' ,
'deepika' , 78 , 90 , 'ramya' ]
list1
print ([list1.index(i) for i in list1 if ( type (i) is str )])
print ([i for i in list1 if ( type (i) is str )])
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3: Using isinstance() function
Python3
list1 = [ 'sravan' , 98 , 'harsha' , 'jyothika' ,
'deepika' , 78 , 90 , 'ramya' ]
print (list1)
list2 = []
for i in list1:
if ( isinstance (i, str )):
list2.append(list1.index(i))
print (list2)
|
Output['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya']
[0, 2, 3, 4, 7]
The time and space complexity of all methods are:
Time Complexity: O(n)
Space Complexity: O(n)
Method 4: Using enumerate() function
Python3
list1 = [ 'sravan' , 98 , 'harsha' , 'jyothika' ,
'deepika' , 78 , 90 , 'ramya' ]
print (list1)
obj = enumerate (list1)
for i in obj:
if ( type (i[ 1 ]) is str ):
print (i[ 0 ])
|
Output['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya']
0
2
3
4
7
Method 5: using isinstance() function
Python3
list1 = [ 'sravan' , 98 , 'harsha' , 'jyothika' ,
'deepika' , 78 , 90 , 'ramya' ]
print (list1)
for i in list1:
if ( isinstance (i, str )):
print (list1.index(i))
|
Output['sravan', 98, 'harsha', 'jyothika', 'deepika', 78, 90, 'ramya']
0
2
3
4
7
Time complexity:O(n)
Auxiliary Space:O(n)