Python – Sort List items on basis of their Digits

When sorting a list based on digit patterns rather than numerical value, we use string manipulation techniques. The sorted() method with lambda function and ljust() helps achieve lexicographic sorting of numbers.

Example

Below is a demonstration of sorting numbers based on their digit patterns ?

my_list = [4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1]

print("The list is:")
print(my_list)

print("The list after normal sorting is:")
my_list_copy = sorted(my_list)
print(my_list_copy)

# Convert to strings to find max length
my_temp_val = list(map(str, my_list))
my_max_length = max(map(len, my_temp_val))

# Sort based on digit patterns using left justification
my_result = sorted(my_list, key=lambda index: str(index).ljust(my_max_length, 'a'))

print("The resultant list sorted by digit patterns is:")
print(my_result)
The list is:
[4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1]
The list after normal sorting is:
[1, 10, 33, 120, 122, 390, 460, 541, 892, 2611, 2909, 4344, 11239, 48292]
The resultant list sorted by digit patterns is:
[10, 11239, 120, 122, 1, 2611, 2909, 33, 390, 4344, 460, 48292, 541, 892]

How It Works

The sorting process involves these steps ?

  • String Conversion: Numbers are converted to strings for lexicographic comparison
  • Left Justification: ljust() pads shorter strings with 'a' characters to ensure uniform length
  • Lambda Function: Provides the custom sorting key based on padded string representation
  • Lexicographic Order: Strings are sorted alphabetically, giving digit-pattern-based ordering

Alternative Approach

Here's a simpler approach without padding ?

numbers = [4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1]

# Sort by string representation directly
result = sorted(numbers, key=str)

print("Original list:", numbers)
print("Sorted by digit patterns:", result)
Original list: [4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1]
Sorted by digit patterns: [1, 10, 11239, 120, 122, 2611, 2909, 33, 390, 4344, 460, 48292, 541, 892]

Conclusion

Sorting numbers by digit patterns uses lexicographic string comparison instead of numerical comparison. The ljust() method with padding ensures consistent string lengths, while key=str provides a simpler alternative for basic digit-pattern sorting.

Updated on: 2026-03-26T01:40:07+05:30

443 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements