Open In App

Python – Prefix frequency in string List

Last Updated : 24 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists, we can have a problem in which we need to get the count of strings that start with a particular substring. This can have an application in web development and general programming. Let us discuss certain ways in which this task can be performed.

Method #1 : Using loop + startswith() 

The combination of the above functions can be used to perform this task. In this, we run a loop for each string in list and employ startswith() to get the strings that start with a particular prefix. 

Python3




# Python3 code to demonstrate
# Prefix frequency in List
# using loop + startswith()
 
# Initializing list
test_list = ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing substring
test_sub = 'gfg'
 
# Prefix frequency in List
# using loop + startswith()
res = 0
for ele in test_list:
    if ele.startswith(test_sub):
        res = res + 1
 
# printing result
print("Strings count with matching frequency : " + str(res))


Output

The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
Strings count with matching frequency : 3

Method #2: Using sum() + startswith() 

The combination of above functions can be used to perform this task. In this, we perform the task of counting using sum() and startswith(), is used to perform task of checking of prefix. 

Python3




# Python3 code to demonstrate
# Prefix frequency in List
# using sum() + startswith()
 
# Initializing list
test_list = ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing substring
test_sub = 'gfg'
 
# Prefix frequency in List
# using sum() + startswith()
res = sum(sub.startswith(test_sub) for sub in test_list)
 
# printing result
print("Strings count with matching frequency : " + str(res))


Output

The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
Strings count with matching frequency : 3

Time Complexity: O(n), where n is the length of the list test_list 
Auxiliary Space: O(1) constant additional space is created 

Method #3 : Using find() method

Python3




# Python3 code to demonstrate
# Prefix frequency in List
 
# Initializing list
test_list = ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing substring
test_sub = 'gfg'
 
# Prefix frequency in List
# using loop + find()
res = 0
for ele in test_list:
    if ele.find(test_sub)==0:
        res = res + 1
             
# printing result
print ("Strings count with matching frequency : " + str(res))


Output

The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
Strings count with matching frequency : 3

Method #4 : Using re

Another approach to solve this problem is using the re (regular expression) module in Python. This can be done using the re.match function to match the regular expression pattern to the start of the string. Here is an example:

Python3




import re
 
# Initializing list
test_list = ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
 
# printing original list
print("The original list is : " + str(test_list))
 
# Initializing substring
test_sub = 'gfg'
 
# Prefix frequency in List using re.match
res = 0
for ele in test_list:
    if re.match(f'^{test_sub}', ele):
        res += 1
 
# printing result
print("Strings count with matching frequency : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
Strings count with matching frequency : 3

Time complexity: O(n * m), where n is the length of the list and m is the length of the prefix.
Auxiliary Space: O(1)

Method #5: Using reduce() and lambda function:

In this method, we are using the reduce() function to apply a lambda function to each element of the list. The lambda function checks if the element starts with the given substring, and if so, it increments the count by 1 else no change.

Python3




from functools import reduce
 
# Initializing list
test_list = ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
 
# Initializing substring
test_sub = 'gfg'
 
# using lambda function to check if a string starts with the given substring
count_func = lambda count, string: count + 1 if string.startswith(test_sub) else count
 
# using reduce() function to apply the lambda function to each element of the list
res = reduce(count_func, test_list, 0)
 
# printing original list
print("The original list is : " + str(test_list))
 
# printing result
print("Strings count with matching frequency : " + str(res))


Output

The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
Strings count with matching frequency : 3

Time complexity: O(n * m) where n is the length of the list and m is the length of the prefix.
Auxiliary Space: O(1)

Method #6: Using the filter() method

Step by step Algorithm:

  1. Initialize a list of strings and a substring to find in the list.
  2. Use the filter() method to create a new iterator that contains only the elements in the list that start with the substring.
  3. Use the len() method to count the number of elements in the iterator.
  4. Print the original list of strings and the number of strings in the list that start with the substring.

Python3




# Initialize a list of strings
test_list = ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
 
# Initialize a substring to find in the list
test_sub = 'gfg'
 
# Create a new iterator that contains only the elements in the list that start with the substring
new_iter = filter(lambda element: element.startswith(test_sub), test_list)
 
# Count the number of elements in the iterator using the len() method
count = len(list(new_iter))
 
# Print the original list of strings
print("The original list is : " + str(test_list))
 
# Print the number of strings in the list that start with the substring
print("Strings count with matching frequency: ", count)


Output

The original list is : ['gfgisbest', 'geeks', 'gfgfreak', 'gfgCS', 'Gcourses']
Strings count with matching frequency:  3

Time complexity: O(n) where n is the length of the list.
Auxiliary Space: O(k) where k is the number of elements in the list that start with the given substring.



Similar Reads

Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Prefix Factorials of a Prefix Sum Array
Given an array arr[] consisting of N positive integers, the task is to find the prefix factorials of a prefix sum array of the given array i.e., [Tex]prefix[i] = (\sum_{0}^{i}arr[i])! [/Tex]. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1 6 720 3628800Explanation:The prefix sum of the given array is {1, 3, 6, 10}. Therefore, prefix factorials of th
10 min read
Python - Convert List to key-value list by prefix grouping
Given a list, convert it to consecutive key-value lists, grouping by a prefix. Input : test_list = ["GFG-1", 4, 6, "GFG-2", 3, "GFG-3", 9, 2], temp = "GF" Output : {'GFG-1': [4, 6], 'GFG-2': [3], 'GFG-3': [9, 2]} Explanation : All grouped till next prefix. Input : test_list = ["MRK-1", 4, 6, "MRK-2", 3, "MRK-3", 9, 2], temp = "MR" Output : {'MRK-1'
8 min read
Python - List Words Frequency in String
Given a List of Words, Map frequency of each to occurrence in String. Input : test_str = 'geeksforgeeks is best for geeks and best for CS', count_list = ['best', 'geeksforgeeks', 'computer'] Output : [2, 1, 0] Explanation : best has 2 occ., geeksforgeeks 1 and computer is not present in string.Input : test_str = 'geeksforgeeks is best for geeks and
4 min read
Python - Sort String list by K character frequency
Given String list, perform sort operation on basis of frequency of particular character. Input : test_list = ["geekforgeekss", "is", "bessst", "for", "geeks"], K = 's' Output : ['bessst', 'geekforgeekss', 'geeks', 'is', 'for'] Explanation : bessst has 3 occurrence, geeksforgeekss has 3, and so on. Input : test_list = ["geekforgeekss", "is", "bessst
4 min read
Python - Specific Characters Frequency in String List
Given a String list, extract frequency of specific characters in the whole strings list. Input : test_list = ["geeksforgeeks is best for geeks"], chr_list = ['e', 'b', 'g', 'f'] Output : {'g': 3, 'e': 7, 'b': 1, 'f' : 2} Explanation : Frequency of certain characters extracted. Input : test_list = ["geeksforgeeks"], chr_list = ['e', 'g'] Output : {'
5 min read
Python | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isdigit() This task can be performed using a combinat
6 min read
Generate a list using given frequency list
Given a list, the task is to generate another list containing numbers from 0 to n, from a given list whose each element is the frequency of numbers in the generated list. Input: freq = [1, 4, 3, 5] Output: [0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3] Explanation: Number = 0 Input[0] = 1 Output = [0] Number =1 Input[1] = 4 Output = [0, 1, 1, 1, 1] (repea
7 min read
Python | Prefix sum list
Nowadays, especially in the field of competitive programming, the utility of computing prefix sum is quite popular and features in many problems. Hence, having a one-liner solution to it would possess a great help. Let's discuss certain way in which this problem can be solved. Method #1: Using list comprehension + sum() + list slicing This problem
4 min read
Python | Split strings in list with same prefix in all elements
Sometimes we face a problem in which we have a list of strings and there are some garbage/unwanted letters at its prefix or suffix or at the specified position uniformly, i.e this extends to all the strings in the list. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + list slicing This task can
5 min read
Practice Tags :
three90RightbarBannerImg