How to Sort an Integer in Python

Let’s say that you have an integer with value of 9271 and you want to sort it either ascending(1279) or descending(9721).

How would you do this in Python? How would you sort an integer in either ascending or descending order?

Sorting our integer

Let’s set our integer to n:

n = 9271
Code language: Python (python)

Now let’s sort it:

sorted([i for i in str(n)]) # This will give us a list in ascending order # ['1', '2', '7', '9']
Code language: Python (python)

We can as easily do it the other way:

sorted([i for i in str(n)], reverse=True) # This will give us a list in descending order # ['9', '7', '2', '1']
Code language: Python (python)

How do we convert our sorted list back to an integer?

s = sorted([i for i in str(n)], reverse=True) int("".join(s)) # 9721
Code language: Python (python)

But can we do this in a single line? Yes!

descending = int("".join(sorted([i for i in str(n)], reverse=True))) print(descending) # 9721
Code language: Python (python)

Ready-made functions to sort integers

If you just want a quick copy/paste, then you can use these functions to sort an integer in python:

def sort_asc(n): return int("".join(sorted([i for i in str(n)]))) def sort_desc(n): return int("".join(sorted([i for i in str(n)], reverse=True)))
Code language: Python (python)

Using our ready-made functions

And here is how to use these functions in how to sort an integer using python:

print(sort_asc(473829)) # 234789 print(sort_desc(473829)) # 987432
Code language: Python (python)
def sort_asc(n): return int("".join(sorted([i for i in str(n)]))) def sort_desc(n): return int("".join(sorted([i for i in str(n)], reverse=True))) print(sort_asc(473829)) # 234789 print(sort_desc(473829)) # 987432
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
3 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Mohammed Muzammil
Mohammed Muzammil
4 months ago

how to find the len of an integer
for eg:
n = 98743
len of n is 5
but int type doesn’t support len function

Mohammed Muzammil
Mohammed Muzammil
4 months ago

thank you

Coen de Groot
Coen de Groot
8 months ago

For a slightly simpler version, sorted(str(n)) also works. A string is also an iterable