VMware ESXi and vSphere Cluster Management

Temporarily Sorting Python Lists with sorted()

Learn how to use Python's sorted() function to display lists in ascending or reverse order without changing the original list.

When you need to show the items in a Python list in a particular order but still need the original order later, use the built-in sorted() function. It creates a new, ordered list instead of changing the source list.

This is called temporary sorting. The sorting affects the result produced for immediate use, such as printing or assigning to another variable, while the original list remains unchanged.

What You Need to Know First

  • A list is an ordered, mutable Python collection. Mutable means that its contents can be changed.
  • An iterable is an object whose items can be traversed one at a time. Lists are iterables, and sorted() can also accept other iterable types.
  • A return value is the result produced by a function. For sorted(), the return value is a new list.
  • Ascending order is the default order, such as A through Z or the smallest number to the largest number.
  • Descending order is the opposite order, such as Z through A or the largest number to the smallest number.

Why Sort a List Temporarily?

Sometimes a program needs to display data in an organized way without losing the order in which the data was originally collected. For example, a list might store names in registration order, while a report needs to display those names alphabetically.

Temporary sorting is useful when the original order has meaning, when the same list will be displayed in several orders, or when another part of the program still depends on the original sequence.

Use sorted() when you want an ordered result but do not want to modify the input list.

The sorted() Built-in Function

sorted() is a Python built-in function. A built-in function is available in Python without importing a separate module.

The basic call form is:

sorted(iterable)

When the iterable is a list, sorted() examines its elements and returns a new list containing those elements in sorted order.

You can use the returned list in several ways:

  • Print it directly.
  • Assign it to a variable.
  • Pass it to another function or use it in another expression.

Sorting Strings Alphabetically

Consider a list of surnames. The original list is in this order:

last_names = ['Jones', 'Antunovich', 'Daniels', 'Thomson']
print(last_names)

Output:

['Jones', 'Antunovich', 'Daniels', 'Thomson']

To display the surnames in alphabetical order, pass the list to sorted():

last_names = ['Jones', 'Antunovich', 'Daniels', 'Thomson']
print(sorted(last_names))

Output:

['Antunovich', 'Daniels', 'Jones', 'Thomson']

The default direction is ascending order. For these strings, that means alphabetically from A through Z.

Reverse Sorting with reverse=True

The sorted() function accepts a keyword argument named reverse. A keyword argument is a named argument written in the form name=value.

Use reverse=True to request descending, or reverse, order:

last_names = ['Jones', 'Antunovich', 'Daniels', 'Thomson']
print(sorted(last_names, reverse=True))

Output:

['Thomson', 'Jones', 'Daniels', 'Antunovich']

reverse=True changes the order of the new list returned by sorted(). It does not change the source list.

CallOrder returnedSource list state
sorted(values)Ascending orderUnchanged
sorted(values, reverse=True)Descending or reverse orderUnchanged

Why the Original List Remains Unchanged

sorted() is non-mutating. This means it does not alter the original object passed to it. Instead, it creates and returns a separate list.

last_names = ['Jones', 'Antunovich', 'Daniels', 'Thomson']
alphabetical_names = sorted(last_names)

print(alphabetical_names)
print(last_names)
print(last_names[0])

Output:

['Antunovich', 'Daniels', 'Jones', 'Thomson']
['Jones', 'Antunovich', 'Daniels', 'Thomson']
Jones

The first item in last_names is still 'Jones'. The sorted result is stored in alphabetical_names, while the source variable keeps its prior order.

Capturing the Sorted Result

Although you can print the return value immediately, assigning it to a variable is useful when you need to use the ordered list more than once.

last_names = ['Jones', 'Antunovich', 'Daniels', 'Thomson']
alphabetical_names = sorted(last_names)
names_descending = sorted(last_names, reverse=True)

print(alphabetical_names)
print(names_descending)
print(last_names)

Descriptive names such as alphabetical_names and names_descending make it clear which ordering each variable contains. The original last_names list remains available in its original order.

Sorting Numeric Values for Display

sorted() also works with comparable numbers:

scores = [72, 95, 81, 64]

print(sorted(scores))
print(sorted(scores, reverse=True))
print(scores)

Output:

[64, 72, 81, 95]
[95, 81, 72, 64]
[72, 95, 81, 64]

The first call returns ascending numeric order, the second returns descending numeric order, and the final print shows that scores was not changed.

Temporary Sorting Compared with Permanent Sorting

Python also provides the list method list.sort(). A method is a function associated with an object. Unlike sorted(), list.sort() orders the existing list in place.

ApproachTypical callChanges original list?Produces a new list?Best use
sorted()sorted(values)NoYesKeep the initial ordering while using a sorted result
list.sort()values.sort()YesNo useful sorted return valueChange the existing list permanently

Use sorted() when preserving the initial order matters. Use list.sort() only when changing the original list is intentional.

Common Syntax Patterns

# Return an ascending sorted list
sorted(list_name)

# Return a descending sorted list
sorted(list_name, reverse=True)

# Save the sorted result
new_list = sorted(list_name)

# Print the sorted result immediately
print(sorted(list_name))

Troubleshooting

The source list did not become sorted

If you write sorted(last_names) without printing or assigning its result, the new list is created and then ignored. Calling sorted() does not modify last_names.

# The result is ignored
sorted(last_names)

# Keep or display the result instead
alphabetical_names = sorted(last_names)
print(alphabetical_names)

If you actually intend to change the original list, use its sort() method:

last_names.sort()

The result is ascending instead of reverse order

The default is ascending order. Include reverse=True inside the call:

sorted(last_names, reverse=True)

Using quotation marks around True

True is a Boolean value, not a string. Write:

sorted(last_names, reverse=True)

Do not write reverse='True'. Quotation marks turn True into text rather than the Boolean value expected for this option.

Assigning list.sort() produces None

A common mistake is expecting list.sort() to return a new sorted list:

ordered_names = last_names.sort()
print(ordered_names)

This prints None because sort() changes the existing list in place and does not return the ordered list. Use sorted(last_names) when you need a separate return value:

ordered_names = sorted(last_names)

Key Points to Remember

  • sorted(iterable) returns a new list in ascending order.
  • sorted(iterable, reverse=True) returns a new list in descending order.
  • The original list remains unchanged because sorted() is non-mutating.
  • Use assignment when you need to keep the sorted result.
  • sorted() is the appropriate choice when the initial ordering must be retained.
  • list.sort() is the related approach for permanently sorting an existing list.

For the related in-place approach, continue with Python list sorting concepts.