Python program to print sorted number formed by merging all elements in array

When it is required to print the sorted numbers that are formed by merging all elements in an array, we can use string manipulation and sorting techniques. The approach involves converting all numbers to strings, joining them together, sorting the digits, and converting back to an integer.

Example

Below is a demonstration of the same ?

def get_sorted_nums(my_num):
    my_num = ''.join(sorted(my_num))
    my_num = int(my_num)
    print(my_num)

def merged_list(my_list):
    my_list = list(map(str, my_list))
    my_str = ''.join(my_list)
    get_sorted_nums(my_str)

my_list = [7, 845, 69, 60, 99, 11]
print("The list is :")
print(my_list)
print("The result is :")
merged_list(my_list)

Output

The list is :
[7, 845, 69, 60, 99, 11]
The result is :
11456678999

How It Works

The solution works in the following steps:

  1. Convert to strings: All numbers in the list are converted to strings using map(str, my_list)
  2. Merge all digits: The strings are joined together using ''.join() to create one long string of digits
  3. Sort digits: Individual digits are sorted using sorted() function
  4. Convert back to integer: The sorted string is converted back to an integer for the final result

Alternative Implementation

Here's a more concise version that combines both functions ?

def merge_and_sort_digits(numbers):
    # Convert all numbers to strings and join them
    merged_string = ''.join(map(str, numbers))
    
    # Sort all digits and convert back to integer
    sorted_number = int(''.join(sorted(merged_string)))
    
    return sorted_number

# Example usage
my_list = [7, 845, 69, 60, 99, 11]
print("The list is :")
print(my_list)
print("The result is :")
print(merge_and_sort_digits(my_list))
The list is :
[7, 845, 69, 60, 99, 11]
The result is :
11456678999

Key Points

  • The map(str, list) function converts all integers in the list to strings
  • The ''.join() method concatenates all strings without any separator
  • The sorted() function sorts individual characters (digits) in ascending order
  • Converting back to int() removes any leading zeros and gives the final numeric result

Conclusion

This program demonstrates how to merge all digits from an array of numbers and sort them to form a new number. The key techniques used are string conversion, joining, sorting, and type conversion back to integer.

Updated on: 2026-03-26T13:16:51+05:30

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements