what is the sort() method in python? How to order by Descending or Ascending?
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
sorted()
andsort()
methods in Python can be used to sort data.I’ll show you how to use the sorted() and sort() methods using code examples and explain the differences between them.
Sort()
method in pythonSort() method accepts a list and arranges it in a specific order. There is no return value for Sort() method.
Below example, We have a list of numbers that we can sort in ascending order using the sort() method.
Unordered list : [34, 21, 1, 345, 47]
Ordered list: [1, 21, 34, 47, 345]
If the list has already been sorted, the console will return None.
key
andreverse
are two optional arguments for Sort() method.sort() method
key
has the value it will be called on each item in the list.sort() method
reverse
has a value it will be called on each item in the list here the value is boolean oftrue
orfalse
. ifreverse=true
means the sorted list will be in reverse alphabetical order.Sorted()
method in pythonThe sorted() method returns a new sorted list from any iterable. Lists, strings, and tuples are examples of iterables.
Sorted() method also having same two optional arguments
key
andreverse
.Below example, A list of numbers has been sorted in ascending order. if we use
reverse=True
computer will reverse the list from greatest to smallest.