Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Prefix frequency in string List

Improve Article
Save Article
  • Last Updated : 22 Sep, 2022
Improve Article
Save Article

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))

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

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

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!