To sort a python list, we can use list sort() and sorted() function. What is the difference between them? In this tutorial, we will discuss this topic.
Python list sort() function
Python list sort() function is defined as:
list.sort(key=..., reverse=...)
Here is an example:
l = [2, 3, 1, 4] l.sort() print(l) l.sort(reverse = True) print(l)
The result will be:
[1, 2, 3, 4] [4, 3, 2, 1]
To konw more about python list sort() function, you can read:
Python Beginner’s Guide to Sort Python List
Python sorted() function
Python sorted() also can sort a python list, it is defined as:
sorted(iterable, /, *, key=None, reverse=False)
We also can use it to sort a python list. Here is an example:
l = [2, 3, 1, 4] print(sorted(l)) print(sorted(l, reverse = True))
The result also is:
[1, 2, 3, 4] [4, 3, 2, 1]
Compare the result, we can find the difference between python list sort() and sorted().
Here is the difference:
Python list sort() | return None |
Python sorted() | return a new sorted list |