Python – Sort String list by K character frequency

When it is required to sort a list of strings based on the K character frequency, the sorted() method and lambda function can be used. This technique counts how many times a specific character appears in each string and sorts accordingly.

Syntax

sorted(iterable, key=lambda string: -string.count(character))

Example

Below is a demonstration of sorting strings by character frequency ?

string_list = ['Hi', 'Will', 'Jack', 'Python', 'Bill', 'Mills', 'goodwill']
print("Original list:")
print(string_list)

K = 'l'
print(f"\nSorting by character '{K}' frequency:")

# Sort by K character frequency (descending order)
result = sorted(string_list, key=lambda word: -word.count(K))

print("Sorted list:")
print(result)

# Show frequency count for each word
print(f"\nFrequency of '{K}' in each word:")
for word in result:
    print(f"'{word}': {word.count(K)} times")
Original list:
['Hi', 'Will', 'Jack', 'Python', 'Bill', 'Mills', 'goodwill']

Sorting by character 'l' frequency:
Sorted list:
['goodwill', 'Will', 'Bill', 'Mills', 'Hi', 'Jack', 'Python']

Frequency of 'l' in each word:
'goodwill': 2 times
'Will': 2 times
'Bill': 2 times
'Mills': 2 times
'Hi': 0 times
'Jack': 0 times
'Python': 0 times

Sorting in Ascending Order

To sort by frequency in ascending order (least frequent first), remove the negative sign ?

string_list = ['Hello', 'Will', 'Bell', 'Python', 'Bill', 'Mills', 'goodwill']
K = 'l'

# Sort by K character frequency (ascending order)
result = sorted(string_list, key=lambda word: word.count(K))

print("Ascending order by 'l' frequency:")
for word in result:
    print(f"'{word}': {word.count(K)} times")
Ascending order by 'l' frequency:
'Python': 0 times
'Will': 2 times
'Bell': 2 times
'Bill': 2 times
'Mills': 2 times
'Hello': 2 times
'goodwill': 2 times

How It Works

  • The sorted() function sorts the list without modifying the original

  • The key parameter specifies a function to extract comparison values

  • lambda word: -word.count(K) counts occurrences of character K in each word

  • The negative sign - reverses the order for descending sort

  • word.count(K) returns the number of times K appears in the word

Conclusion

Use sorted() with lambda word: -word.count(K) to sort strings by character frequency in descending order. Remove the negative sign for ascending order sorting.

Updated on: 2026-03-26T01:08:50+05:30

433 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements