sort list in python

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.py
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

my_list.sort()

print(my_list)
76 chars
6 lines

Output:

main.py
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
34 chars
2 lines

To sort a list in descending order, you can pass the reverse=True argument to the sort() function:

main.py
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

my_list.sort(reverse=True)

print(my_list)
88 chars
6 lines

Output:

main.py
[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
34 chars
2 lines

If you want to use the sorted() function to sort a list, here's an example:

main.py
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

sorted_list = sorted(my_list)

print(sorted_list)
95 chars
6 lines

Output:

main.py
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
34 chars
2 lines

Note that the sorted() function returns a new sorted list, while the original list my_list remains unchanged.

gistlibby LogSnag