Open In App

Python - Ways to determine common prefix in set of strings

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A common prefix is the longest substring that appears at the beginning of all strings in a set. Common prefixes in a set of strings can be determined using methods like os.path.commonprefix() for quick results, itertools.takewhile() combined with zip() for a more flexible approach, or iterative comparison.

For Example we are given a list s = ["flower", "flow", "flight"] we need to find the common prefix which is "fl" in this case so the output will be "fl".

Using os.path.commonprefix()

This method from the os module finds the longest prefix common to all strings in a list.

Python
import os

s = ["flower", "flow", "flight"]
c_pref = os.path.commonprefix(s)
print(c_pref)  

Output
fl

Explanation:

  • Function finds the longest common prefix from a list of strings by comparing them character by character.
  • It returns 'fl', as it is the shared starting substring among "flower", "flow", and "flight"

Using itertools.takewhile()

itertools.takewhile() to find the common prefix character by character.

Python
from itertools import takewhile

s = ["flower", "flow", "flight"]
c_pref = ''.join(
    ch[0] for ch in takewhile(lambda x: all(c == x[0] for c in x), zip(*s))
)
print(c_pref)  

Output
fl

Explanation:

  • Groups corresponding characters from each string in the list s. For example, zip(*s) creates tuples like ('f', 'f', 'f'), ('l', 'l', 'l'), etc.
  • Iterates over these tuples, keeping characters as long as all elements in the tuple are identical. The common prefix is then constructed by joining the first character of each valid tuple.

Using str.startswith() in a Loop

Start with the first string and iteratively check if it’s a prefix for the remaining strings, reducing its length as needed.

Python
s = ["flower", "flow", "flight"]
if not s:
    c_pref = ""
else:
    c_pref = s[0]
    for s in s[1:]:
        while not s.startswith(c_pref):
            c_pref = c_pref[:-1]
            if not c_pref:
                break
print(c_pref)  

Output
fl

Explanation:

  • First string is set as the initial common prefix, and the rest are checked against it.
  • If a string doesn’t match, the prefix is shortened until a match is found or the prefix becomes empty.

Practice Tags :

Similar Reads