Python – Sort by Uppercase Frequency

Sorting strings by uppercase frequency means arranging them based on the count of capital letters they contain. This is useful for organizing text data by capitalization patterns. Python's sort() method with a custom key function makes this straightforward.

How It Works

The approach uses a custom function that counts uppercase letters in each string, then sorts the list using this count as the sorting key ?

def count_uppercase(text):
    return len([char for char in text if char.isupper()])

words = ["pyt", "is", "FUN", "to", "Learn"]

print("Original list:")
print(words)

words.sort(key=count_uppercase)

print("Sorted by uppercase frequency:")
print(words)
Original list:
['pyt', 'is', 'FUN', 'to', 'Learn']
Sorted by uppercase frequency:
['pyt', 'is', 'to', 'Learn', 'FUN']

Using Lambda Function

You can make the code more concise using a lambda function instead of defining a separate function ?

words = ["Hello", "WORLD", "python", "Code", "AI"]

print("Original list:")
print(words)

words.sort(key=lambda x: sum(1 for char in x if char.isupper()))

print("Sorted by uppercase count:")
print(words)
Original list:
['Hello', 'WORLD', 'python', 'Code', 'AI']
Sorted by uppercase count:
['python', 'Hello', 'Code', 'AI', 'WORLD']

Sorting in Descending Order

To sort from highest to lowest uppercase frequency, use the reverse=True parameter ?

words = ["abc", "DEF", "GHi", "jkl", "MNO"]

def uppercase_count(text):
    return sum(1 for char in text if char.isupper())

words.sort(key=uppercase_count, reverse=True)

print("Sorted by uppercase frequency (descending):")
print(words)

# Show the counts for clarity
for word in words:
    count = uppercase_count(word)
    print(f"'{word}' has {count} uppercase letters")
Sorted by uppercase frequency (descending):
['DEF', 'MNO', 'GHi', 'abc', 'jkl']
'DEF' has 3 uppercase letters
'MNO' has 3 uppercase letters
'GHi' has 2 uppercase letters
'abc' has 0 uppercase letters
'jkl' has 0 uppercase letters

Key Points

  • The isupper() method returns True for uppercase characters

  • List comprehension efficiently counts uppercase letters

  • The sort() method modifies the original list in-place

  • Use sorted() if you want to keep the original list unchanged

Conclusion

Sorting by uppercase frequency is achieved using a custom key function that counts capital letters. This technique is useful for text processing and organizing strings by their capitalization patterns.

Updated on: 2026-03-26T00:59:27+05:30

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements