Sorting a List in Python

To sort a list in Python, you can use the list.sort() method of the list. The sort() method modifies the list in place. To get a copy of the sorted list without modifying the original list, you can use the sorted(list) function, which returns a new sorted list. To sort the list in reverse order, you can use the reverse parameter for the list.sort(reverse=True) method. You can also provide a custom function to sort the list with your rules. For example, sort the list by odd and even elements or by the internal properties of an object in the list. In this Python Sorting a List example, we use the default list.sort() method. You can find more advanced sorting examples below in this article. Click Execute to run the Python Sort a List example online and see the result.
Sorting a List in Python Execute
a = [4, 3, 1, 2]
a.sort()
print(a)
Updated: Viewed: 4912 times

What is the List in Python?

Lists in Python are an ordered collection of objects that allow you to store and organize data. Lists can contain items of different data types, such as numbers, strings, classes, and even other lists. Lists in Python are dynamic structures; you can add, remove, or sort lists "in place" using list manipulation techniques. The get the length of the list, you can use the len() function.

To create a list and initialize with values, you can enclose the values in square brackets, separated by commas.

Create and initialize Python list
my_list = [1, 3, 2, 4]

print(my_list)

# [1, 3, 2, 4]

Unlike some programming languages, lists in Python can be made up of various types of objects:

Create and initialize a Python list with objects of different types
my_list = [1, "Hello", 2, "World", True]

print(my_list)

# [1, 'Hello', 2, 'World', True]

What is Sorting?

Sorting is a method of sorting a list in a meaningful order. Sorting makes a list more efficient for analysis and visualization. The importance of sorting is that data retrieval can be optimized to a high level if the data is stored sorted. Sorts are also used to present data in more readable formats.

What is List sort() in Python?

The sort() method is a built-in Python method that sorts the list in ascending order by default, but you can change the order from ascending to descending by specifying the sort criteria. To sort a list, you need to use the "sort()" function.

Python list sort example
a = [4, 3, 1, 2]
a.sort()

print(a)

# [1, 2, 3, 4]

sort() Parameters

By default, sort() requires no additional parameters, but it does have two optional parameters:

1. Reverse

To sort the objects in descending order, you need to use the "reverse" parameter and set it to "True":

Python list reverse example
a = [1, 2, 3, 4]
a.sort(reverse=True)

print(a)

# [4, 3, 2, 1]

2. Key

If you need your sorting implementation, the sort method accepts a "key" function that serves as a key for comparing sorts. Let's return first even and then odd elements:

Python list key example
def cmp(x):
  return x % 2, x
a = [4, 3, 1, 2]
a.sort(key=cmp)

print(a)

# [2, 4, 1, 3]

You can use the "key" parameter and set the lambda function as the value to increase which will sort the list:

Python lambda functions example
a = [4, 3, 1, 2]
a.sort(key=lambda x: (x % 2, x))

print(a)

# [2, 4, 1, 3]

What are Lambda Functions in Python?

In Python, a lambda function is an anonymous one-line function that can have any number of arguments but can only have one expression. A lambda function can behave like a regular function declared using the Python "def" keyword. Usually, a lambda function is passed as an argument to another function. To use a lambda function, you need to specify the lambda keyword, then the variables used by the function, and what the function will return.

Lambda function example
square_sum = lambda x, y: x ** 2 + y ** 2

print(square_sum(1, 2))

# 5

Instead of a lambda function, you can rewrite this example using a regular function. You will end up with a code that does the same:

Function example
def square_sum(x, y):
  return x ** 2 + y ** 2;

print(square_sum(1, 2))

# 5

What does sorted() do in Python?

For sorting, you can also use the "sorted" method and specify the list you want to sort as the first parameter. The Python sorted() function returns a sorted list from an iterable object. The sorted method sorts any sequence (list, tuple) and returns a list with elements sorted without changing the original sequence.

Python sorted example
a = [4, 3, 1, 2]
b = sorted(a)

print(a)
print(b)

# [4, 3, 1, 2]
# [1, 2, 3, 4]

Using this sorted() method, you can also specify the "key" and "reverse" parameters:

Python sorted parameters example
a = [4, 3, 1, 2]
b = sorted(a, key=lambda x: (x == 1, x), reverse=True)

print(a)
print(b)

# [4, 3, 1, 2]
# [1, 4, 3, 2]

What is the difference between sort() and sorted()?

The main difference between sort() and sorted() - sort() modifies the list directly and does not return any value, whereas sorted() does not modify the list and returns the sorted list. If you want to sort the list but still have the original unsorted version, you can use the sorted() function. If keeping the original order in the list is not essential, you can call the sort() function from the list.

How to sort the characters of a string?

Strings in Python are a list of characters, so you can sort them where you get the sorted characters as a result. For sorted characters, you can use the sorted () method:

Sort string of characters example
a = 'JustDoIt'
      
print(sorted(a))

# ['D', 'I', 'J', 'o', 's', 't', 't', 'u']

See also