Skip to content
Related Articles

Related Articles

Python – Group list by first character of string

View Discussion
Improve Article
Save Article
  • Last Updated : 06 Sep, 2022
View Discussion
Improve Article
Save Article

Sometimes, we have a use case in which we need to perform the grouping of strings by various factors, like first letter or any other factor. These types of problems are typical to database queries and hence can occur in web development while programming. This article focuses on one such grouping by the first letter of the string. Let’s discuss certain ways in which this can be performed. 

Method #1: Using next() + lambda + loop 

The combination of the above 3 functions is used to solve this particular problem by the naive method. The lambda function performs the task of finding like initial character, and the next function helps in forwarding iteration. 

Python3




# Python3 code to demonstrate
# Initial Character Case Categorization
# using next() + lambda + loop
 
# initializing list
test_list = ['an', 'a', 'geek', 'for', 'g', 'free']
 
# printing original list
print("The original list : " + str(test_list))
 
# using next() + lambda + loop
# Initial Character Case Categorization
 
 
def util_func(x, y): return x[0] == y[0]
 
 
res = []
for sub in test_list:
    ele = next((x for x in res if util_func(sub, x[0])), [])
    if ele == []:
        res.append(ele)
    ele.append(sub)
 
# print result
print("The list after Categorization : " + str(res))

Output : 

The original list : ['an', 'a', 'geek', 'for', 'g', 'free']
The list after Categorization : [['an', 'a'], ['geek', 'g'], ['for', 'free']]

Method #2: Using sorted() + groupby() 

This particular task can also be solved using the groupby function which offers a convenient method to solve this problem. The sorted function sorts the elements by initial character to be feed to groupby for the relevant grouping. 

Python3




# Python3 code to demonstrate
# Initial Character Case Categorization
# using sorted() + groupby()
from itertools import groupby
 
# initializing list
test_list = ['an', 'a', 'geek', 'for', 'g', 'free']
 
# printing original list
print("The original list : " + str(test_list))
 
# using sorted() + groupby()
# Initial Character Case Categorization
 
 
def util_func(x): return x[0]
 
 
temp = sorted(test_list, key=util_func)
res = [list(ele) for i, ele in groupby(temp, util_func)]
 
# print result
print("The list after Categorization : " + str(res))

Output : 

The original list : ['an', 'a', 'geek', 'for', 'g', 'free']
The list after Categorization : [['an', 'a'], ['geek', 'g'], ['for', 'free']]

Method #3: Using for loop

Python3




# Python3 code to demonstrate
# Initial Character Case Categorization
 
# initializing list
test_list = ['an', 'a', 'geek', 'for', 'g', 'free']
 
# printing original list
print("The original list : " + str(test_list))
 
res = []
x=[]
for i in test_list:
    if i[0] not in x:
        x.append(i[0])
for i in x:
    p=[]
    for j in test_list:
        if j[0]==i:
            p.append(j)
    res.append(p)
             
# print result
print("The list after Categorization : " + str(res))

Output

The original list : ['an', 'a', 'geek', 'for', 'g', 'free']
The list after Categorization : [['an', 'a'], ['geek', 'g'], ['for', 'free']]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!