HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

Python Sort Lists


In Python, you can sort lists using the sorted() function or by using the sort() method.

Using the sorted() function:


Example
# Creating an unsorted list
my_list = [3, 1, 4, 1, 5, 9, 2, 6]

# Sorting the list using sorted() function
sorted_list = sorted(my_list)

print(sorted_list)  # Output: [1, 1, 2, 3, 4, 5, 6, 9]
                 
             

Using the sort() method (modifies the original list in place)

Example
# Creating an unsorted list
my_list = [3, 1, 4, 1, 5, 9, 2, 6]

# Sorting the list using sort() method
my_list.sort()

print(my_list)  # Output: [1, 1, 2, 3, 4, 5, 6, 9]

                 
             

Reverse Order

The reverse() method reverses the current sorting order of the elements.

You can also sort lists in reverse order by specifying the reverse=True parameter in both methods:

Example
# Sorting the list in reverse order using sorted() function
sorted_reverse_list = sorted(my_list, reverse=True)
print(sorted_reverse_list)  # Output: [9, 6, 5, 4, 3, 2, 1, 1]

# Sorting the list in reverse order using sort() method
my_list.sort(reverse=True)
print(my_list)  # Output: [9, 6, 5, 4, 3, 2, 1, 1]