How to sort a list in Python?

In Python, a list can be sorted in two ways: The list.sort() method and the sorted() built-in function. The main difference is that the list.sort() method actually changes the list, while the sorted() function returns a new list and the original list remains unchanged. Another difference is that, the sort() method is only defined for lists, while the sorted() function can be used for other iterables like dictionaries as well.

# how to sort a list in python
list_sort = [1, 5, 2, 3, 6, 4]

# sort list via sorted() built-in function
list_sorted = sorted(list_sort)

# sort list via sort() method

# print both results

In this code, the list is sorted twice. Once via the sorted() built-in function and then via the list.sort() method. Both results are the same and are printed in the final part of the code.

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

To learn more, refer to the reference pages for the built-in sorted() function and the list.sort() method.