To sort a list in Python, you can use either the sort()
function or the sorted()
function. The sort()
function sorts the list in place, meaning it modifies the original list, while the sorted()
function returns a new sorted list and leaves the original list unchanged.
Here is an example of how to use the sort()
function to sort a list in ascending order:
main.py76 chars6 lines
Output:
main.py34 chars2 lines
To sort a list in descending order, you can pass the reverse=True
argument to the sort()
function:
main.py88 chars6 lines
Output:
main.py34 chars2 lines
If you want to use the sorted()
function to sort a list, here's an example:
main.py95 chars6 lines
Output:
main.py34 chars2 lines
Note that the sorted()
function returns a new sorted list, while the original list my_list
remains unchanged.
gistlibby LogSnag