Open In App

Python | Count String occurrences in mixed list

Last Updated : 14 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Check String occurrences in mixed list
# using isinstance() + list comprehension
 
# initialize list
test_list = ['gfg', 1, True, 'is', 2, 'best']
 
# printing original list
print("The original list : " + str(test_list))
 
# Check String occurrences in mixed list
# using isinstance() + list comprehension
res = len([val for val in test_list if isinstance(val, str)])
 
# printing result
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




# Python3 code to demonstrate working of
# Check String occurrences in mixed list
# using sum() + isinstance() + generator expression
 
# initialize list
test_list = ['gfg', 1, True, 'is', 2, 'best']
 
# printing original list
print("The original list : " + str(test_list))
 
# Check String occurrences in mixed list
# using sum() + isinstance() + generator expression
res = sum(isinstance(ele, str) for ele in test_list)
 
# printing result
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




# Python3 code to demonstrate working of
# Check String occurrences in mixed list
 
# initialize list
test_list = ['gfg', 1, True, 'is', 2, 'best']
 
# printing original list
print("The original list : " + str(test_list))
 
# Check String occurrences in mixed list
x = []
for i in test_list:
    if(type(i) is str):
        x.append(i)
res = len(x)
# printing result
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




# Python3 code to demonstrate working of
# Check String occurrences in mixed list
# initialize list
test_list = ['gfg', 1, True, 'is', 2, 'best']
 
# printing original list
print("The original list : " + str(test_list))
 
# Check String occurrences in mixed list
res = 0
for val in test_list:
try:
    val + ""
    res += 1
except TypeError:
    pass
 
# printing result
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




# Initialize the mixed list
mixed_list = ['gfg', 1, True, 'is', 2, 'best']
 
# Use the filter function and a lambda function to filter the list
filtered_list = filter(lambda x: isinstance(x, str), mixed_list)
 
# Use the len function to get the length of the filtered list
count = len(list(filtered_list))
 
# Print the count
print(count)
 
 
# This code is contributed Vinay Pinjala.


Output

3

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:

  1. Create a list of mixed data types, including strings, integers, and booleans.
  2. Print the original list using the print() function and string concatenation to display the list.
  3. Use the filter() function to apply a filter on the list using a lambda function.
  4. The lambda function checks if the element is an instance of string or not using the isinstance() function.
  5. The filter() function returns a filter object, which is converted into a list using the list() function.
  6. The len() function is used to find the length of the filtered list, which is the number of strings in the original list.
  7. Print the result using the print() function and string concatenation to display the number of strings in the list.

Python3




# Python3 code to demonstrate working of
# Check String occurrences in mixed list
# using filter() and isinstance()
 
# initialize list
test_list = ['gfg', 1, True, 'is', 2, 'best']
 
# printing original list
print("The original list : " + str(test_list))
 
# Check String occurrences in mixed list
# using filter() and isinstance()
res = len(list(filter(lambda x: isinstance(x, str), test_list)))
 
# printing result
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:

  1. Import the reduce function from the functools module.
  2. Initialize the test_list with a list of mixed elements.
  3. Pass a lambda function as the first argument to the reduce function which takes two arguments – an accumulator (acc) and the current element (x).
  4. 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.
  5. The reduce function iterates over each element of the list, applies the lambda function, and returns the final accumulated value.
  6. The final accumulated value is the count of the number of strings in the list.
  7. Print the original list and the count of the number of strings in the list.

Python3




from functools import reduce
# initialize list
test_list = ['gfg', 1, True, 'is', 2, 'best']
 
# printing original list
print("The original list : " + str(test_list))
 
res = reduce(lambda acc, x: acc + isinstance(x, str), test_list, 0)
# printing result
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:

  1. Initialize a mixed list test_list.
  2. Print the original list.
  3. Use the map() function along with a lambda function to get a boolean value for each element of the list.
  4. Use the sum() function to sum up the boolean values to get the count of strings.
  5. Print the count of strings in the list.

Python3




# Python3 code to demonstrate working of
# Check String occurrences in mixed list
 
# initialize list
test_list = ['gfg', 1, True, 'is', 2, 'best']
 
# printing original list
print("The original list : " + str(test_list))
 
# Check String occurrences in mixed list
# using map() + lambda
res = sum(map(lambda x: isinstance(x, str), test_list))
 
# printing result
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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads