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
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']
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']
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
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
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)))
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
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