Open In App

Python – Count Strings with substring String List

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

The classical problem that can be handled quite easily by python and has been also dealt with many times is finding if a string is substring of other. But sometimes, one wishes to extend this on list of strings and find how many strings satisfy condition, and hence then requires to traverse the entire container and perform the generic algorithm. Lets discuss certain ways to perform this task. 

Method #1 : Using list comprehension + len() List comprehension is an elegant ways to perform any particular task as it increases readability in a long run. This task can be performed using naive method and hence can be reduced to list comprehension as well. The len() is used to compute length of list. 

Python3




# Python code to demonstrate
# Count Strings with substring String List
# using list comprehension + len()
 
# initializing list
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing substring
subs = 'Geek'
 
# using list comprehension + len()
# Count Strings with substring String List
res = len([i for i in test_list if subs in i])
 
# printing result
print ("All strings count with given substring are : " + str(res))


Output : 

The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are : 2

Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.

Method #2 : Using filter() + lambda + len() This function can also perform this task of finding the strings with the help of lambda. It just filters out all the strings matching the particular substring and then adds it in a new list. The len() is used to compute length of list. 

Python3




# Python code to demonstrate
# Count Strings with substring String List
# using filter() + lambda + len()
 
# initializing list
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing substring
subs = 'Geek'
 
# using filter() + lambda + len()
# Count Strings with substring String List
res = len(list(filter(lambda x: subs in x, test_list)))
 
# printing result
print ("All strings count with given substring are : " + str(res))


Output : 

The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are : 2

Time Complexity: O(n) where n is the number of elements in the string list. The sum() + generator expression  is used to perform the task and it takes O(n) time.
Auxiliary Space: O(1) constant additional space needed

Method #3 : Using find() method

Approach 

  1. Initiated a for loop to traverse the list
  2. Used the find() method to check whether the substring is present in each element of list
  3. If present increment the res variable
  4. Display the res variable

Python3




# Python code to demonstrate
# Count Strings with substring String List
 
# initializing list
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing substring
subs = 'Geek'
 
 
# Count Strings with substring String List
res = 0
for i in test_list:
    if i.find(subs)!=-1:
        res+=1
 
# printing result
print ("All strings count with given substring are : " + str(res))


Output

The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are : 2

Time Complexity : O(N)
Auxiliary Space : O(1)

Method #4 : Using operator.contains() method

Approach:

  1. Initiated a for loop to traverse the list
  2. Used the operator.contains() method to check whether the substring is present in each element of list
  3. If present increment the res variable
  4. Display the res variable

Python3




# Python code to demonstrate
# Count Strings with substring String List
 
# initializing list
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing substring
subs = 'Geek'
 
 
# Count Strings with substring String List
res = 0
import operator
for i in test_list:
    if operator.contains(i,subs):
        res+=1
 
# printing result
print ("All strings count with given substring are : " + str(res))


Output

The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are : 2

Time Complexity : O(N)
Auxiliary Space : O(1)

Method #5: Using list comprehension + count()

This method uses list comprehension to generate a list of 1s and 0s based on whether the substring exists in each string. Then, sum() function is used to count the number of 1s in the list.

Python3




# Python code to demonstrate
# Count Strings with substring String List
 
# initializing list
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
 
# printing original list
print ("The original list is : " + str(test_list))
 
# initializing substring
subs = 'Geek'
 
# Count Strings with substring String List
res = sum(1 for s in test_list if s.count(subs)>0)
 
# printing result
print ("All strings count with given substring are : " + str(res))


Output

The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are : 2

Time complexity: O(n*m), where n is the length of the list and m is the length of the longest string in the list.
Auxiliary space: O(1) (excluding the space used to store the list)

Method #6: reduce() function from functools module:

Algorithm:

  1. Import reduce() function from functools module.
  2. Initialize the list of strings and the substring.
  3. Define a lambda function to check if the substring is present in the string.
  4. Use reduce() function to count the number of strings that contain the substring.
  5. Print the count of such strings.

Python3




from functools import reduce
 
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
subs = 'Geek'
# printing original list
print ("The original list is : " + str(test_list))
  
count = reduce(lambda x, y: x + 1 if subs in y else x, test_list, 0)
# printing result
print("All strings count with given substring are :", count)
#This code is contributed by Jyothi pinjala.


Output

The original list is : ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are : 2

Time complexity: O(n), where n is the number of strings in the input list. This is because we need to iterate over each string in the list to check if the substring is present.

Space complexity: O(1). This is because we are only storing a few variables like the input list, substring, and the count of strings containing the substring. No new list or data structure is being created.

Method 7: using for loop

  • Initialize the input list of strings test_list and print it.
  • Initialize the substring subs.
  • Initialize a counter variable count to zero.
  • Use a for loop to iterate through each string in test_list.
  • Check if the substring subs is present in the current string.
  • If it is, increment the counter variable count.
  • After the loop is finished, print the value of count.

Python3




# Python code to demonstrate
# Count Strings with substring String List
# using for loop
 
# initializing list
test_list = ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
 
# printing original list
print("The original list is: " + str(test_list))
 
# initializing substring
subs = 'Geek'
 
# using for loop
count = 0
for string in test_list:
    if subs in string:
        count += 1
 
# printing result
print("All strings count with given substring are: " + str(count))


Output

The original list is: ['GeeksforGeeks', 'Geeky', 'Computers', 'Algorithms']
All strings count with given substring are: 2

time complexity of this method is O(nk), where n is the length of the list and k is the length of the substring. The auxiliary space required is O(1) because we are only using a counter variable.



Similar Reads

Python | Filter list of strings based on the substring list
Given two lists of strings string and substr, write a Python program to filter out all the strings in string that contains string in substr. Examples: Input : string = ['city1', 'class5', 'room2', 'city2']substr = ['class', 'city']Output : ['city1', 'class5', 'city2'] Input : string = ['coordinates', 'xyCoord', '123abc']substr = ['abc', 'xy']Output
8 min read
Python | Finding strings with given substring in list
Method #1: Using list comprehension List comprehension is an elegant way to perform any particular task as it increases readability in the long run. This task can be performed using a naive method and hence can be reduced to list comprehension as well. C/C++ Code # Python code to demonstrate # to find strings with substrings # using list comprehens
8 min read
Python | Check if substring is part of List of Strings
Many problems of substrings have been dealt with many times. There can also be such problem in which we require to check if argument string is a part of any of the strings coming in the input list of strings. Let's discuss various ways in which this can be performed. Method #1 : Using join() The basic approach that can be employed to perform this p
5 min read
Python | Replace substring in list of strings
While working with strings, one of the most used application is replacing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the replacement of a substring in list of string is performed. Let's discuss certain ways in which this can be performed. Method #1 : Using list
6 min read
Python - Substring presence in Strings List
Given list of substrings and list of string, check for each substring, if they are present in any of strings in List. Input : test_list1 = ["Gfg", "is", "best"], test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"] Output : [True, False, False] Explanation : Only Gfg is present as substring in any of list String in 2nd list. Input : te
5 min read
Python - All occurrences of Substring from the list of strings
Given a list of strings and a list of substring. The task is to extract all the occurrences of a substring from the list of strings. Examples: Input : test_list = ["gfg is best", "gfg is good for CS", "gfg is recommended for CS"] subs_list = ["gfg", "CS"] Output : ['gfg is good for CS', 'gfg is recommended for CS'] Explanation : Result strings have
5 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Python | Ways to count number of substring in string
Given a string and a substring, write a Python program to find how many numbers of substrings are there in the string (including overlapping cases). Let's discuss a few methods below. Method #1: Using re.findall() Method C/C++ Code # Python code to demonstrate # to count total number # of substring in string import re # Initialising string s = 'aba
4 min read
Python | Count overlapping substring in a given string
Given a string and a sub-string, the task is to get the count of overlapping substring from the given string. Note that in Python, the count() function returns the number of substrings in a given string, but it does not give correct results when two occurrences of the substring overlap. Consider this example - C/C++ Code string = "Geeksfor
2 min read
Python - Possible Substring count from String
Given target string and argument substring, count how many substrings can be constructed using string characters, repetitions not allowed. Input : test_str = "geksefokesgergeeks", arg_str = "geeks" Output : 3 Explanation : "geeks" can be created 3 times using string characters. Input : test_str = "gefroksefokesgergeeks", arg_str = "for" Output : 2
4 min read
Practice Tags :
three90RightbarBannerImg