Reorder items in a list

Reorder items in a list#

Lists in Python are ordered collections of items. You can reorder the items in a list using the sort method or by manually moving items around in the list. So let’s start with an example of how you can print an unsorted list as items at index 2 and 3 are not in order.

Print an unsorted list#
l = ['a', 'b', 'd', 'c', 'e']
print(l)  # ['a', 'b', 'd', 'c', 'e']

Below is an example of how you can reorder items in a list with the sort method and is in this case sufficient as the items are sorted in ascending order. With the parameter reverse=True, you can sort the items in descending order. And with the parameter key, you can specify a custom sorting function.

Reorder items in a list with the sort method#
l = ['a', 'b', 'd', 'c', 'e']
l.sort()
print(l)  # ['a', 'b', 'c', 'd', 'e']

In some cases reordering items in a list manually can be more efficient than using the sort method. Below is an example of how you can reorder items in a list manually. In this example, the item at index 2 is moved to index 3 by popping it from the list and inserting it at the new index with the insert method and the pop method.

Reorder items in a list manually#
l = ['a', 'b', 'd', 'c', 'e']
l.insert(3, l.pop(2))
print(l)    # ['a', 'b', 'c', 'd', 'e']

The sort method is useful when you want to sort the items in a list in ascending or descending order. If you need a custom sorting method, you can use the key argument of the sort method to specify a custom sorting function. But understanding how to reorder items in a list manually can be useful in some cases where the sort method is not suitable.