Open In App

Prefix frequency in string List – Python

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore various methods to find prefix frequency in string List. The simplest way to do is by using a loop.

Using a Loop

One of the simplest ways to calculate the frequency of a prefix in a list of strings is by iterating through each element and checking if the string starts with the given prefix.

Python
a = ["geeks", "geeksforgeeks", "geeky", "geek", "apple", "banana"]

# Prefix to match
prefix = "geeks"

# Initialize count
count = 0

# Loop through the list and check
# if each word starts with the given prefix
for word in a:
    if word.startswith(prefix):
        count += 1

print(f"The prefix '{prefix}' appears {count} times.")

Output
The prefix 'geeks' appears 2 times.

Explanation:

  • word.startswith(prefix): Checks if each word starts with the given prefix.
  • count: Tracks how many words start with the specified prefix.

Using List Comprehension

List comprehension is a more compact and Pythonic way to solve this problem we can implement the above method in a single line.

Python
a = ["geeks", "geeksforgeeks", "geeky", "geek", "apple", "banana"]

# Prefix to match
prefix = "geeks"

# Using list comprehension to count 
# words starting with the given prefix
count = len([word for word in a if word.startswith(prefix)])

print(f"The prefix '{prefix}' appears {count} times.")

Output
The prefix 'geeks' appears 2 times.

Explanation:

  • List comprehension iterates through each word in the list and checks if it starts with the given prefix.
  • len() calculates the length of the filtered list results in count of words that match.

Using filter()

The filter() function can filter strings starting with the prefix, then we are counting the filtered results using len() method.

Python
a = ["geeks", "geeksforgeeks", "geeky", "geek", "apple", "banana"]

# Prefix to match
prefix = "geeks"

# Using filter to count words starting with the given prefix
count = len(list(filter(lambda word: word.startswith(prefix), a)))

print(f"The prefix '{prefix}' appears {count} times.")

Output
The prefix 'geeks' appears 2 times.

Using collections.Counter()

To calculate the frequency of multiple prefixes, we can use Counter for efficient counting.

Python
from collections import Counter

a = ["geeks", "geeksforgeeks", "geeky", "geek", "apple", "banana"]

# Prefix to match
prefix = "geeks"

# Count all prefixes in the list
prefixes = [word[:len(prefix)] for word in a]  # Extract the prefixes
prefix_count = Counter(prefixes)

# Get the count for the desired prefix
count = prefix_count[prefix]

print(f"The prefix '{prefix}' appears {count} times.")

Output
The prefix 'geeks' appears 2 times.


Practice Tags :

Similar Reads