Hi everyone! Sometimes you need to sort the list in ascending and descending order. There is a very simple solution to this issue;)
Actually, I described some options here. But – in the standard Python distribution there is a library heapq , which I will not describe the full functionality of now (I will describe later, yes), and which will help us organize the sorting of the list in ascending and descending order. Let me give you an example that allows you to sort a list in ascending and descending order in just one line. So:
import random #connected a library for working with random numbers
import heapq #connected a library for working with list
list=[random.randrange(1,1000) for i in range(100)] #Generated a list consisting of random numbers, where random.randrange (1,1000) is a random number from 1 to 1000, range (100) is the number of elements in the created list
print(list) #Output the resulting list to the console
print(heapq.nsmallest(len(list), list)) #Displayed the result of sorting the list in ascending order
print(heapq.nlargest(len(list), list)) #Displayed the result of sorting the list in descending order
As you can see, everything is simple. And without magic. Thanks for attention! As always – if you have any questions, write to the mail or Telegram.
Support the Blog!
Running a blog takes a lot of effort, time, and passion. Your donations help improve the content, inspire new ideas, and keep the project going.
If you’ve enjoyed the blog’s materials, any support would mean the world to me. Thank you for being here! ❤️