Sometimes, while working with data, we can have a problem in which we need to check for the occurrences of a particular data type. In this, we can also have a problem in which we need to check for string occurrences. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using isinstance() + list comprehension
The combination of above methods can be used to perform this task. In this, we check for each element of list for the string instance and built list with only string, and return it’s length.
Python3
test_list = [ 'gfg' , 1 , True , 'is' , 2 , 'best' ]
print ( "The original list : " + str (test_list))
res = len ([val for val in test_list if isinstance (val, str )])
print ( "Number of strings in list : " + str (res))
|
Output :
The original list : ['gfg', 1, True, 'is', 2, 'best']
Number of strings in list : 3
Time complexity: O(n)
Where n is the length of the input list.
Auxiliary space: O(m)
Where m is the number of string elements in the input list.
Method #2: Using sum() + isinstance() + generator expression
The combination of the above functionalities can be used to perform this task. In this, we compute the True instances of string check and return its sum counting string instances.
Python3
test_list = [ 'gfg' , 1 , True , 'is' , 2 , 'best' ]
print ( "The original list : " + str (test_list))
res = sum ( isinstance (ele, str ) for ele in test_list)
print ( "Number of strings in list : " + str (res))
|
Output :
The original list : ['gfg', 1, True, 'is', 2, 'best']
Number of strings in list : 3
Time Complexity: O(n), where n is the length of the input list. This is because we’re using sum() + isinstance() + generator expression which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using constant additional space.
Method #3 : Using type() and len() methods
The combination of the above functions can be used to check the type of the element, if the type if str then we can append that element to a new list and print the size of the new list.
Python3
test_list = [ 'gfg' , 1 , True , 'is' , 2 , 'best' ]
print ( "The original list : " + str (test_list))
x = []
for i in test_list:
if ( type (i) is str ):
x.append(i)
res = len (x)
print ( "Number of strings in list : " + str (res))
|
Output
The original list : ['gfg', 1, True, 'is', 2, 'best']
Number of strings in list : 3
Method #4: Using try/except
Python3
test_list = [ 'gfg' , 1 , True , 'is' , 2 , 'best' ]
print ( "The original list : " + str (test_list))
res = 0
for val in test_list:
try :
val + ""
res + = 1
except TypeError:
pass
print ( "Number of strings in list : " + str (res))
|
Output
The original list : ['gfg', 1, True, 'is', 2, 'best']
Number of strings in list : 3
Time Complexity: O(n) where n is the length of the input list
Auxiliary Space: O(1) as we are using a single variable ‘res’ to store the count.
This method uses the fact that trying to add a string to an empty string is allowed, but trying to add other types to an empty string will raise a TypeError exception. So we can use a try-except block to check if the current element in the list is a string or not. As soon as an exception is encountered, we increment the count variable ‘res’ and move to the next element in the list.
Method #5: Using the filter() function and a lambda function
Python3
mixed_list = [ 'gfg' , 1 , True , 'is' , 2 , 'best' ]
filtered_list = filter ( lambda x: isinstance (x, str ), mixed_list)
count = len ( list (filtered_list))
print (count)
|
Time Complexity: O(n) where n is the length of the input list
Auxiliary Space: O(n)
Method #6: Using filter() and isinstance()
Use the filter() function along with the isinstance() function to filter out the string elements from the given list and then find the length of the resulting list.
Approach:
- Create a list of mixed data types, including strings, integers, and booleans.
- Print the original list using the print() function and string concatenation to display the list.
- Use the filter() function to apply a filter on the list using a lambda function.
- The lambda function checks if the element is an instance of string or not using the isinstance() function.
- The filter() function returns a filter object, which is converted into a list using the list() function.
- The len() function is used to find the length of the filtered list, which is the number of strings in the original list.
- Print the result using the print() function and string concatenation to display the number of strings in the list.
Python3
test_list = [ 'gfg' , 1 , True , 'is' , 2 , 'best' ]
print ( "The original list : " + str (test_list))
res = len ( list ( filter ( lambda x: isinstance (x, str ), test_list)))
print ( "Number of strings in list : " + str (res))
|
Output
The original list : ['gfg', 1, True, 'is', 2, 'best']
Number of strings in list : 3
Time complexity: O(n), where n is the length of the input list, as we need to iterate over each element of the list to check its type.
Auxiliary space: O(n), as we are creating a filtered list of string elements, which can be of maximum size n.
Method #7: Using the reduce() and isinstance() functions.
Algorithm:
- Import the reduce function from the functools module.
- Initialize the test_list with a list of mixed elements.
- Pass a lambda function as the first argument to the reduce function which takes two arguments – an accumulator (acc) and the current element (x).
- The lambda function checks whether the current element is an instance of the string type or not, and increments the accumulator by 1 if it is a string.
- The reduce function iterates over each element of the list, applies the lambda function, and returns the final accumulated value.
- The final accumulated value is the count of the number of strings in the list.
- Print the original list and the count of the number of strings in the list.
Python3
from functools import reduce
test_list = [ 'gfg' , 1 , True , 'is' , 2 , 'best' ]
print ( "The original list : " + str (test_list))
res = reduce ( lambda acc, x: acc + isinstance (x, str ), test_list, 0 )
print ( "Number of strings in list : " + str (res))
|
Output
The original list : ['gfg', 1, True, 'is', 2, 'best']
Number of strings in list : 3
Time complexity of the reduce function is O(n), where n is the number of elements in the list. The lambda function inside the reduce function has a time complexity of O(1) as it performs a constant number of operations. Therefore, the overall time complexity of the algorithm is O(n).
Auxiliary space of the algorithm is also O(n) as we are using a list to store the original elements.
Method #8: Using the map() function and lambda
Step-by-step algorithm:
- Initialize a mixed list test_list.
- Print the original list.
- Use the map() function along with a lambda function to get a boolean value for each element of the list.
- Use the sum() function to sum up the boolean values to get the count of strings.
- Print the count of strings in the list.
Python3
test_list = [ 'gfg' , 1 , True , 'is' , 2 , 'best' ]
print ( "The original list : " + str (test_list))
res = sum ( map ( lambda x: isinstance (x, str ), test_list))
print ( "Number of strings in list : " + str (res))
|
Output
The original list : ['gfg', 1, True, 'is', 2, 'best']
Number of strings in list : 3
Time complexity: O(n) where n is the length of the list
Space complexity: O(1) as we are not using any extra space
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
14 Apr, 2023
Like Article
Save Article