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`:

 ``````1 `````` ``````n = 9271 ``````

Now let’s sort it:

 ``````1 2 3 4 `````` ``````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:

 ``````1 2 3 4 `````` ``````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?

 ``````1 2 3 4 `````` ``````s = sorted([i for i in str(n)], reverse=True) int("".join(s)) # 9721 ``````

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

 ``````1 2 3 4 5 `````` ``````descending = int("".join(sorted([i for i in str(n)], reverse=True))) print(descending) # 9721 ``````

 ``````1 2 3 4 5 `````` ``````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))) ``````
 ``````1 2 3 4 5 `````` ``````print(sort_asc(473829)) # 234789 print(sort_desc(473829)) # 987432 ``````
 `````` 1 2 3 4 5 6 7 8 9 10 11 `````` ``````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 ``````