How to Sort a List in Python?

Ways to sort a list in Python

The sort() function belongs to the list class in Python and can help to sort a list in Python. This function will sort the list in ascending order by default.

To sort a list in Python:

  1. Use the sort() function to sort a list in Python.
# Sort a list in Python
list_new = [3,5,1,7]
# Use the sort() function to sort a list in Python
list_new.sort()
print(list_new)
# Output: [1, 3, 5, 7]

The sort() function sorts the original list in Python. A list of strings will be sorted alphabetically in the above example.

To sort a list in descending order, set the reverse parameter as True. Alternatively, we can also provide the comparison key for each element of the list using the key parameter.

The sorted() function can also sort a list in Python. This function returns a new sorted list and does not modify the original list.

To sort a list in Python:

  1. Use the sorted() function to sort a list in Python.
# Sort a list in Python
list_new = [3,5,1,7]
# Use the sorted() function to sort a list in Python
sort_list = sorted(list_new)
print(sort_list)
# Output: [1, 3, 5, 7]    

The key and reverse parameters can be used with the sorted() function as well.

We can also use traditional sorting techniques like Bubble Sort, Quick Sort, Merge Sort, and more to sort a list in Python.

Let us observe a sample of Quick Sort Algorithm.

# Sort a list in Python
def quicksort_algo(list_new):
    if not list_new:
        return []
    return (quicksort_algo([x for x in list_new[1:] if x <  list_new[0]])
            + [list_new[0]] +
            quicksort_algo([x for x in list_new[1:] if x >= list_new[0]]))
list_new = [3,5,1,7]
# Use the Quick Sort algo to sort a list in Python
sort_list = quicksort_algo(list_new)
print(sort_list)
# Output: [1, 3, 5, 7]

To conclude

This particular article demonstrates several methods to sort a list in Python. To achieve this, we used the sort() and sorted() functions. An example of the Quick Sort algorithm is also demonstrated.

Explore more from this category at Python Lists. Alternatively, search and view other topics at All Tutorials.