Write a Python program to split a list based on first character of word


This program is using the itertools library's groupby function to group a list of strings (a) by their first letter. The program first sorts the list using the built-in sorted function, then uses the groupby function to group the list by the first letter of each string. The key parameter of the groupby function is set to itemgetter(0), which is a function that returns the first item of the input. This is used to group the list by the first letter of each string.

The program then uses a for loop to iterate through each letter and the corresponding list of words that start with that letter. For each letter, the letter is printed, followed by the list of words starting with that letter, each on a new line and indented. The program also uses another for loop to iterate through the list of words, and print each word. This program will group the given list of words by the first letter of the word, and print them in an organized manner.

Source Code

from itertools import groupby
from operator import itemgetter
 
a = ["cat","dog","cow","tiger","lion","Fox","Shark","Snake","turtle","mouse","monkey","bear"]
 
for ltr, wds in groupby(sorted(a), key=itemgetter(0)):
	print(ltr)
	for w in wds:
		print(" ",w)
	print("")
 

Output

F
  Fox
S
  Shark
  Snake
b
  bear
c
  cat
  cow
d
  dog
l
  lion
m
  monkey
  mouse
t
  tiger
  turtle


Example Programs