Python Example | Sort a Python List

In this python example, we will introduce some methods for sorting a python list.

Method 1: list.sort() function

We can use python built-in function to sort a list.

For example:

org_list = [3, 1, 4, 5, 2]

org_list.sort()
print(org_list)
# [1, 2, 3, 4, 5]

Here we have used org_list.sort() to sort python list org_list.

We should notice: org_list.sort() function return None, it will change the value of org_list.

We also can sort python list reversely.

For example:

org_list.sort(reverse=True)
print(org_list)
# [5, 4, 3, 2, 1]

Method 2: use python sorted() function

We also can use python sorted() function to sort a list. We should notice that this function will return a new list.

For example:

org_list = [3, 1, 4, 5, 2]

new_list = sorted(org_list)
print(org_list)
print(new_list)
# [3, 1, 4, 5, 2]
# [1, 2, 3, 4, 5]

Here new_list is a new python list, which is a sorted list.

We also can sort python list reversely.

For example:

new_list_reverse = sorted(org_list, reverse=True)
print(org_list)
print(new_list_reverse)
# [3, 1, 4, 5, 2]
# [5, 4, 3, 2, 1]

Method 3: use bubble sort algorithm

Here is the example code:

Python Example | Implement Bubble Sort