Как отсортировать список в порядке убывания python
Перейти к содержимому

Как отсортировать список в порядке убывания python

  • автор:

Как отсортировать список в порядке убывания python

Этот метод по очереди сравнивает каждые два соседних элемента и переставляет их местами, если порядок неправильный. Например, возьмем следующий ряд чисел: 67381. Сначала алгоритм сравнит первые два соседних числа: 6 меньше 7, значит порядок правильный, они остаются на своих местах. Затем следующие два числа – 7 больше 3, значит они меняются местами. Затем он сравнит 7 и 8, и тоже переставит их местами и так далее. После первого прохода по ряду чисел в конце окажется самое большое число – 8. И дальше алгоритм проходит по всем числам снова и будет проходить столько раз, пока каждое число не встанет на свое место – от меньшего к большему.

Вот как это выглядит на языке Питон. Есть список с числами в рандомном порядке, который нужно отсортировать. Сперва сравним первые два числа и поменяем их местами, если порядок неправильный – то есть второе число больше первого. И попросим распечатать получившийся список.

Этот код сравнил 6 с 7, и оставил их на своих местах. Теперь сравним следующие два числа: меняем в коде индексы на 1 и 2. И видим, что он сравнил 3 и 7 и поменял их местами.

Эту операцию нам надо выполнять столько раз, сколько у нас в списке чисел, чтобы каждое из них нашло свое место. Поэтому чтобы не прописывать для каждой пары одну и ту же операцию, мы создаем цикл, равный длине нашего массива минус 1, потому что последнее число в списке не имеет соседа справа, и значит эту операцию сравнения производить не нужно. И просим распечатать получившийся список внутри цикла, чтобы видеть каждый шаг кода.

Этот код постепенно переместил 8 в конец, после одного обхода одно число нашло свое правильное место. Но на этом сортировка не заканчивается. Нам нужно, чтобы каждый элемент массива переместился на свое место – значит нужно сделать столько обходов, сколько у нас чисел. Поэтому мы создаем новый цикл с количеством итераций, равным длине списка. Но здесь мы увидим, что на последнем обходе ничего не поменяется, потому что когда 3 нашла свое место, самый минимальный элемент 1 тоже встал на свое место, значит мы можем отнять 1, чтобы не делать последний обход. Как еще можно оптимизировать этот код? После каждого обхода в конце списка оказывается наибольшее число, и сравнение тех чисел, которые уже нашли свое место, производить не надо. Поэтому мы можем отнять внутри цикла количество обходов, соответствующее итерации цикла – run. Тогда код не будет выполнять лишних операций сравнения.

Давайте теперь превратим наш алгоритм в функцию, которой можно будет передавать любые другие массивы. И протестируем ее на новом списке.

Встроенные методы и функции сортировки

В Python есть встроенные функции и методы сортировки, которые позволяют проделать те же операции одной строчкой кода. В большинстве случаев программисты обходятся ими, но алгоритмы, пример которого мы только что протестировали, важно освоить, чтобы понимать механизм работы этих встроенных функций и методов. И в отдельных случаях, когда данных так много, что встроенные функции и методы сортируют их слишком долго, суметь написать более быструю программу.

Метод .sort() сортирует список и сохраняет его в отсортированном виде. А функция sorted() создает новый отсортированный список без изменения исходного.

Еще одно их отличие в том, что функция sorted работает не только со списками, но и другими объектами. Например, вот что получится, если мы отсортируем строку.

Эта функция возвращает список каждый раз, несмотря на то, какой тип данных был ей передан. В случае со словарями, она возвращает отсортированный список словарных ключей.

По умолчанию сортировка будет происходить по возрастанию, но мы можем передавать функции и методу параметры. За это отвечает параметр reverse. Если мы передадим ему параметр True, сортировка будет происходить по убыванию.

Кроме этого, у sort и sorted есть параметр key, который указывает на функцию сравнения. Например, если мы хотим отсортировать значения без учета регистра текста, можно сделать так:

Внутри параметра key могут находиться не только встроенные функции, но и написанные нами. Они обычно нужны, когда мы хотим отсортировать сложный объект. Например, есть такая проблема: если попытаться отсортировать сложный объект (который состоит, например, из списка списков), сортировка будет выполняться по первому элементу.

Если мы хотим, чтобы сортировка происходила не по первому элементу, мы можем сами создать специальную функцию.

С помощью функций мы можем производить сортировку и внутри словарей – например, отсортировать эти данные по доходу супруги чиновника из ФСБ.

Теперь вы умеете сортировать данные с помощью Python. Тетрадку этого урока можно скачать на нашем GitHub.

Как сортировать списки в Python

В Python вы можете использовать метод sort() для сортировки списка на месте. Или вы можете использовать встроенную функцию sorted(), чтобы получить отсортированную копию списка.

В этом уроке вы узнаете:

  • Синтаксис метода sort() и функции sorted()
  • Примеры кода сортировки списков по возрастанию и убыванию
  • Настроить сортировку по ключевому параметру
  • Разница между sort() и sorted()

Синтаксис метода Python sort()

Метод sort() работает со списком Python. И он сортирует список на месте — и изменяет исходный список.

Синтаксис метода Python sort():

Давайте теперь разберем приведенный выше синтаксис.

  • — любой допустимый объект списка Python.
  • reverse — необязательный параметр, который принимает значение True или False.
  • Значение по умолчанию для reverse равно False, и список отсортирован в порядке возрастания. Дайте True, чтобы отсортировать список в порядке убывания.
  • key также является необязательным параметром, для которого задано значение .
  • может быть встроенной или определяемой пользователем функцией.

В следующем разделе вы начнете кодировать простые примеры.

Как отсортировать список Python в порядке возрастания

Рассмотрим список номеров. Чтобы отсортировать список в порядке возрастания, вы можете вызвать метод sort() в списке.

▶ Запустите следующий фрагмент кода.

Номера списка были отсортированы в порядке возрастания, а исходный список был изменен. Это называется сортировкой на месте.

Как отсортировать список Python по убыванию

Чтобы отсортировать список в порядке убывания, установите для параметра reverse значение True, как показано ниже.

Вы можете видеть, что список теперь отсортирован в порядке убывания.

Как использовать ключ с методом Python sort()

В этом разделе давайте воспользуемся ключевым параметром и настроим сортировку.

Здесь mod5() — это функция, которая принимает число x и возвращает остаток при делении числа x на 5.

И мы хотели бы использовать вышеуказанную функцию в качестве ключа.

Теперь запустите следующую ячейку кода.

Потратьте минуту, чтобы проанализировать вывод.

Обратите внимание, что вместо обычной сортировки вы теперь настраиваете свою сортировку в соответствии с ключом mod5.

  • Теперь первым идет число, которое оставляет минимальный остаток при делении на 5.
  • И число, которое оставляет наибольший остаток при делении на 5, является последним элементом в отсортированном списке.

Чтобы убедиться, что это так, запустите следующий фрагмент кода.

5 точно делит 25, а остаток равен 0. Итак, это первый элемент в отсортированном списке. 6 оставляет остаток 1, так что это второй элемент, и так далее. 9 оставляет остаток 4 при делении на 5, и это последний элемент в отсортированном списке.

Вместо того, чтобы определять отдельную функцию, вы могли бы также использовать лямбда-функции. В Python лямбды — это однострочные анонимные функции. lambda args : выражение возвращает выражение, вычисленное для аргументов.

Теперь давайте перепишем приведенную выше сортировку, используя лямбда-выражение, как показано ниже.

Итак, вы узнали, как сортировать список чисел. Далее давайте посмотрим, как можно отсортировать список строк в Python.

Как отсортировать список Python в алфавитном порядке

В этом разделе вы научитесь сортировать список строк на примерах, вдохновленных Гарри Поттером. ✨

В нашем примере студенты — это список студентов Хогвартса. И мы хотели бы отсортировать их в алфавитном порядке их имен.

При сортировке списка строк сортировка по умолчанию выполняется в алфавитном порядке.

Распечатаем отсортированный список, чтобы проверить результат сортировки.

Как отсортировать список Python в обратном алфавитном порядке

Чтобы отсортировать список в обратном алфавитном порядке, установите reverse = True, как показано во фрагменте кода ниже.

Из вывода видно, что список действительно отсортирован в обратном порядке.

Как использовать ключевой параметр Настройка сортировки

В этом разделе давайте настроим сортировку, используя необязательный ключевой параметр.

Рассмотрим следующий список, дома.

Здесь дома — это список словарей. Каждый словарь содержит две пары ключ-значение, одна из которых обозначает имена студентов, а другая — дом, к которому они принадлежат.

Теперь мы хотели бы отсортировать этот список домов в алфавитном порядке домов, которым они принадлежат.

Как вы уже могли догадаться, мы должны установить ключевой параметр дома конкретных студентов.

Чтобы получить дом каждого студента, вы можете определить функцию returnHouse(), как показано ниже.

Эта функция возвращает дом, которому принадлежит конкретный студент.

Теперь вы можете вызвать метод sort() для списка домов, как показано на рисунке.

В приведенном ниже выводе обратите внимание, как список отсортирован по домам, а не по именам студентов. Вот почему у нас есть Гриффиндор, Хаффлпафф и Слизерин — в алфавитном порядке.

Чтобы соответствующим образом определить ключевой параметр, вы также можете использовать лямбда-функцию. Для каждого элемента списка эта функция возвращает дом для этого элемента списка.

▶ Запустите следующую ячейку кода, чтобы убедиться в этом.

Во всех предыдущих примерах вы использовали метод sort() для списка. И теперь вы знаете, что он изменяет исходный список.

Что, если вы хотите сохранить исходный список как есть, но получить отсортированную копию списка?

Что ж, в Python для этого можно использовать функцию sorted().

Синтаксис функции Python sorted()

Функция sorted() принимает в качестве аргумента список или любую коллекцию. И он возвращает отсортированную копию списка, а исходный список не изменяется.

Синтаксис функции sorted() в Python:

Обратите внимание, что синтаксис очень похож на метод sort(), который мы видели ранее.

  • — любой допустимый объект списка Python и обязательный параметр.
  • reverse и key являются необязательными параметрами

Примечание. В отличие от метода sort(), который работает только со списками, функцию sorted() можно использовать для сортировки любого итерируемого объекта Python, например списков, строк и словарей.

Как отсортировать список Python с помощью функции sorted()

№1. В этом примере nums — это список чисел.

Вы можете вызвать функцию sorted() с числами в качестве аргумента. И присвоить его списку sorted_nums1.

В приведенном выше выводе вы можете видеть, что nums по умолчанию отсортированы в порядке возрастания.

Также обратите внимание, что исходный список nums не изменяется, потому что sorted() возвращает новый список. Это проверяется ниже.

№ 2. Теперь установите для необязательного параметра reverse значение True и получите sorted_nums2.

Как показано в кодовой ячейке ниже, sorted_nums2 — это новый список с элементами, отсортированными в порядке убывания.

№3. В этом примере давайте поработаем со списком строк.

Как и в предыдущих примерах, вызов функции sorted() возвращает новый список. И элементы отсортированы в алфавитном порядке.

№ 4. Теперь давайте настроим сортировку, используя необязательный ключевой параметр. Установите ключ на len. Это отсортирует список на основе длины строк.

Примечание. В Python встроенная функция len() принимает любые итерируемые объекты, такие как списки, строки, кортежи и т. д. И он возвращает длину итерации.

Строка с наименьшей длиной появляется первой в отсортированном списке, а самая длинная строка появляется в конце отсортированного списка.

В выходных данных выше груша — самая короткая строка, а клубника — самая длинная строка.

Метод Python sort() и функция sorted()

Итак, вы узнали, как использовать метод sort(), а также функцию sorted(). В этом разделе давайте перечислим различия между этими двумя методами.

Метод Python .sort() Функция Python sorted() Сортирует список на месте — изменяет исходный список. Возвращает новый отсортированный список. Работает только со списками Python. Работает с итерируемыми объектами Python, такими как списки, строки и другие коллекции.

Подведение итогов ��‍��

Я надеюсь, что вы нашли этот учебник по спискам Python полезным.

Давайте быстро подведем итог тому, что мы рассмотрели.

  • Используйте list.sort(reverse = True | False, key = ) с необязательными параметрами reverse и key для сортировки списка на месте.
  • Используйте sorted(list, reverse = True | False, key = ), чтобы получить отсортированную копию списка.

Теперь, когда вы узнали, как сортировать списки Python, узнайте, как интерпретировать списки в Python. Или вы также можете научиться обрабатывать файлы или работать с файлами JSON в Python.

Сортировка списка Python

Сортировка данных — одна из самых распространенных задач при работе с Python. Например, вы можете отсортировать список членов команды по именам или список проектов в порядке приоритета.

В этой статье описывается, как сортировать списки в Python .

Python sort() и sorted()

В Python, вы можете сортировать список с помощью встроенного в list.sort() метод или встроенный в sorted() функцию.

Функция sorted() создает новый отсортированный список, а метод list.sort() сортирует список на месте. Если вы хотите сохранить, несортированный список используйте функцию sorted() . Еще одно отличие состоит в том, что функция sorted sorted() работает с любым итерируемым объектом.

Синтаксис sort() и sorted() следующий:

Необязательные ключевые аргументы key и reverse имеют следующее значение:

  • key — функция, которая принимает один аргумент и преобразует его перед сравнением. Функция должна возвращать одно значение, которое используется для сравнения сортировки.
  • reverse — значение reverse может быть True или False . Значение по умолчанию — True . Если для этого аргумента установлено значение false, список сортируется в обратном порядке.

Элементы списка сравниваются с помощью оператора «меньше чем» ( < ) и сортируются в порядке возрастания. Оператор < не поддерживает сравнение строки с целым числом, поэтому, если у вас есть список, содержащий строки и целые числа, операция сортировки завершится ошибкой.

В следующем примере показано, как отсортировать список строк в алфавитном порядке:

Если вы хотите сохранить исходный список без изменений, используйте функцию sorted() :

Чтобы отсортировать список в обратном (по убыванию) порядке, установите reverse аргумент в True :

Сортировка с функцией

Аргумент key принимает функцию и позволяет выполнять более сложные операции сортировки.

Самый простой пример — отсортировать элементы по их длине:

Мы используем функцию len() чтобы вернуть количество символов в строке, которая используется в качестве компаратора:

Вы также можете создать пользовательскую функцию и использовать ее в качестве key аргумента для сравнения. Вот пример, показывающий, как отсортировать список целых чисел по сумме их цифр:

Другой пример — использование ключевого аргумента для сортировки сложного списка, такого как список кортежей:

Мы используем анонимную (лямбда) функцию, которая возвращает первый элемент кортежа. Список отсортирован по значению, возвращаемому функцией:

Тот же подход можно использовать для сортировки списка словарей:

Лямбда-функция возвращает значение ключа name , которое используется для сравнения:

Лучший и более быстрый способ сортировки сложной функции — использовать функции модуля Оператор . Вот пример:

Функция itemgetter извлекает значение symbol ключа:

Выводы

Мы показали вам, как сортировать списки в Python с помощью метода sort() и функции sorted() .

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

How to Use sorted() and sort() in Python

All programmers will have to write code to sort items or data at some point. Sorting can be critical to the user experience in your application, whether it’s ordering a user’s most recent activity by timestamp, or putting a list of email recipients in alphabetical order by last name. Python sorting functionality offers robust features to do basic sorting or customize ordering at a granular level.

In this guide, you’ll learn how to sort various types of data in different data structures, customize the order, and work with two different methods of sorting in Python.

By the end of this tutorial, you’ll know how to:

  • Implement basic Python sorting and ordering on data structures
  • Differentiate between sorted() and .sort()
  • Customize a complex sort order in your code based on unique requirements

For this tutorial, you’ll need a basic understanding of lists and tuples as well as sets. Those data structures will be used in this tutorial, and some basic operations will be performed on them. Also, this tutorial uses Python 3, so example output in this tutorial might vary slightly if you’re using Python 2.

Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

Ordering Values With sorted()

To get started with Python sorting, you’re first going to see how to sort both numeric data and string data.

Sorting Numbers

You can use Python to sort a list by using sorted() . In this example, a list of integers is defined, and then sorted() is called with the numbers variable as the argument:

The output from this code is a new, sorted list. When the original variable is printed, the initial values are unchanged.

This example shows four important characteristics of sorted() :

  1. The function sorted() did not have to be defined. It’s a built-in function that is available in a standard installation of Python.
  2. sorted() , with no additional arguments or parameters, is ordering the values in numbers in an ascending order, meaning smallest to largest.
  3. The original numbers variable is unchanged because sorted() provides sorted output and does not change the original value in place.
  4. When sorted() is called, it provides an ordered list as a return value.

This last point means that sorted() can be used on a list, and the output can immediately be assigned to a variable:

In this example, there is now a new variable numbers_sorted that stored the output of sorted() .

You can confirm all of these observations by calling help() on sorted() . The optional arguments key and reverse will be covered later in the tutorial:

Technical Detail: If you’re transitioning from Python 2 and are familiar with its function of the same name, you should be aware of a couple important changes in Python 3:

  1. Python 3’s sorted() does not have a cmp parameter. Instead, only key is used to introduce custom sorting logic.
  2. key and reverse must be passed as keyword arguments, unlike in Python 2, where they could be passed as positional arguments.

If you need to convert a Python 2 cmp function to a key function, then check out functools.cmp_to_key() . This tutorial will not cover any examples using Python 2.

sorted() can be used on tuples and sets very similarly:

Notice how even though the input was a set and a tuple, the output is a list because sorted() returns a new list by definition. The returned object can be cast to a new type if it needs to match the input type. Be careful if attempting to cast the resulting list back to a set, as a set by definition is unordered:

The numbers_set_sorted value when cast to a set is not ordered, as expected. The other variable, numbers_tuple_sorted , retained the sorted order.

Sorting Strings

str types sort similarly to other iterables, like list and tuple. The example below shows how sorted() iterates through each character in the value passed to it and orders them in the output:

sorted() will treat a str like a list and iterate through each element. In a str , each element means each character in the str . sorted() will not treat a sentence differently, and it will sort each character, including spaces.

.split() can change this behavior and clean up the output, and .join() can put it all back together. We will cover the specific order of the output and why it is that way shortly:

The original sentence in this example is converted into a list of words instead of leaving it as a str . That list is then sorted and combined to form a str again instead of a list.

Limitations and Gotchas With Python Sorting

It is worth noting some limitations and odd behavior that can arise when you’re using Python to sort values besides integers.

Lists With Non-Comparable Data Types Can’t Be sorted()

There are data types that can’t be compared to each other using just sorted() because they are too different. Python will return an error if you attempt to use sorted() on a list containing non-comparable data. In this example, a None and an int in the same list can’t be sorted because of their incompatibility:

This error shows why Python can’t sort the values given to it. It’s trying to put the values in order by using the less than operator ( < ) to determine which value is lower in sorting order. You can replicate this error by manually comparing the two values:

The same TypeError is thrown when you try to compare two non-comparable values without using sorted() .

If the values within the list can be compared and will not throw a TypeError , then the list can be sorted. This prevents sorting iterables with intrinsically unorderable values and producing output that may not make sense.

For example, should the number 1 come before the word apple ? However, if a iterable contains a combination of integers and strings that are all numbers, they can be cast to comparable data types by using a list comprehension:

Each element in mixed_numbers has int() called on it to convert any str values to int values. sorted() is then called and can successfully compare each element and provide a sorted output.

Python can also implicitly convert a value to another type. In the example below, the evaluation of 1 <= 0 is a false statement, so the output of the evaluation will be False . The number 1 can be converted to True as a bool type, while 0 converts to False .

Even though the elements in the list look different, they can all be converted to Booleans ( True or False ) and compared to each other using sorted() :

‘A’ == ‘B’ and 1 <= 0 are converted to False and returned in the ordered output.

This example illustrates an important aspect of sorting: sort stability. In Python, when you sort equal values, they will retain their original order in the output. Even though the 1 moved, all the other values are equal so they retain their original order relative to each other. In the example below, all the values are considered equal and will retain their original positions:

If you inspect the original order and the sorted output, you will see that 1 == 2 is converted to False , and all sorted output is in the original order.

When You’re Sorting Strings, Case Matters

sorted() can be used on a list of strings to sort the values in ascending order, which appears to be alphabetically by default:

However, Python is using the Unicode Code Point of the first letter in each string to determine ascending sort order. This means that sorted() will not treat the names Al and al the same. This example uses ord() to return the Unicode Code Point of the first letter in each string:

name[0] is returning the first character in each element of sorted(names_with_case) , and ord() is providing the Unicode Code Point. Even though a comes before M in the alphabet, the code point for M comes before a , so the sorted output has M first.

If the first letter is the same, then sorted() will use the second character to determine order, and the third character if that is the same, and so on, all the way to the end of the string:

Each value of very_similar_strs is identical except for the last character. sorted() will compare the strings, and because the first five characters are the same, the output will be based on the sixth character.

Strings that contain identical values will end up sorted shortest to longest due to the shorter strings not having elements to compare to with the longer strings:

The shortest string, h , is ordered first with the longest, hhhhh , ordered last.

Using sorted() With a reverse Argument

As shown in the help() documentation for sorted() , there is an optional keyword argument called reverse , which will change the sorting behavior based on the Boolean assigned to it. If reverse is assigned True , then the sorting will be in descending order:

The sorting logic remains the same, meaning that the names are still being sorted by their first letter. But the output has been reversed with the reverse keyword set to True .

When False is assigned, the ordering will remain ascending. Any of the previous examples can be used to see the behavior of reverse using both True or False :

sorted() With a key Argument

One of the most powerful components of sorted() is the keyword argument called key . This argument expects a function to be passed to it, and that function will be used on each value in the list being sorted to determine the resulting order.

To demonstrate a basic example, let’s assume the requirement for ordering a specific list is the length of the strings in the list, shortest to longest. The function to return the length of a string, len() , will be used with the key argument:

The resulting order is a list with a string order of shortest to longest. The length of each element in the list is determined by len() and then returned in ascending order.

Let’s return to the earlier example of sorting by first letter when the case is different. key can be used to solve that problem by converting the entire string to lowercase:

The output values have not been converted to lowercase because key does not manipulate the data in the original list. During sorting, the function passed to key is being called on each element to determine sort order, but the original values will be in the output.

There are two main limitations when you’re using functions with the key argument.

First, the number of required arguments in the function passed to key must be one.

The example below shows the definition of an addition function that takes two arguments. When that function is used in key on a list of numbers, it fails because it is missing a second argument. Each time add() is called during the sort, it is only receiving one element from the list at a time:

The second limitation is that the function used with key must be able to handle all the values in the iterable. For example, you have a list of numbers represented as strings to be used in sorted() , and key is going to attempt to convert them to numbers using int . If a value in the iterable can’t be cast to an integer, then the function will fail:

Each numeric value as a str can be converted to int , but four can’t. This causes a ValueError to be raised and explain that four can’t be converted to int because it is invalid.

The key functionality is extremely powerful because almost any function, built-in or user-defined, can be used to manipulate the output order.

If the ordering requirement is to order an iterable by the last letter in each string (and if the letter is the same, then to use the next letter), then a function can be defined and then used in the sorting. The example below defines a function that reverses the string passed to it, and then that function is used as the argument for key :

The word[::-1] slice syntax is used to reverse a string. Each element will have reverse_word() applied to it, and the sorting order will be based on the characters in the backwards word.

Instead of writing a standalone function, you can use a lambda function defined in the key argument.

A lambda is an anonymous function that:

  1. Must be defined inline
  2. Doesn’t have a name
  3. Can’t contain statements
  4. Will execute just like a function

In the example below, the key is defined as a lambda with no name, the argument taken by the lambda is x , and x[::-1] is the operation that will be performed on the argument:

x[::-1] is called on each element and reverses the word. That reversed output is then used for sorting, but the original words are still returned.

If the requirement changes, and the order should be reversed as well, then the reverse keyword can be used alongside the key argument:

lambda functions are also useful when you need to sort class objects based on a property. If you have a group of students and need to sort them by their final grade, highest to lowest, then a lambda can be used to get the grade property from the class :

This example uses namedtuple to produce classes with name and grade attributes. The lambda calls getattr() on each element and returns the value for grade .

reverse is set to True to make the ascending output flipped to be descending so that the highest grades are ordered first.

The possibilities are endless for how ordering can be done when you leverage both the key and reverse keyword arguments on sorted() . Code can be kept clean and short when you use a basic lambda for a small function, or you can write a whole new function, import it, and use it in the key argument.

Ordering Values With .sort()

The very similarly named .sort() differs quite a bit from the sorted() built-in. They accomplish more or less the same thing, but the help() documentation for list.sort() highlights two of the most critical differences between .sort() and sorted() :

First, sort is a method of the list class and can only be used with lists. It is not a built-in with an iterable passed to it.

Second, .sort() returns None and modifies the values in place. Let’s take a look at the impacts of both of these differences in code:

There are some pretty dramatic differences in how .sort() operates compared to sorted() in this code example:

  1. There is no ordered output of .sort() , so the assignment to a new variable only passes a None type.
  2. The values_to_sort list has been changed in place, and the original order is not maintained in any way.

These differences in behavior make .sort() and sorted() absolutely not interchangeable in code, and they can produce wildly unexpected outcomes if one is used in the wrong way.

.sort() has the same key and reverse optional keyword arguments that produce the same robust functionality as sorted() . Here, you can sort a list of phrases by the second letter of the third word and return the list in reverse:

In this sample, a lambda is used to do the following:

  1. Split each phrase into a list of words
  2. Find the third element, or word in this case
  3. Find the second letter in that word

When to Use sorted() and When to Use .sort()

You’ve seen the differences between sorted() and .sort() , but when do you use which?

Let’s say there is a 5k race coming up: The First Annual Python 5k. The data from the race needs to be captured and sorted. The data that needs to be captured is the runner’s bib number and the number of seconds it took to finish the race:

As the runners cross the finish line, each Runner will be added to a list called runners . In 5k races, not all runners cross the starting line at the same time, so the first person to cross the finish line might not actually be the fastest person:

Each time a runner crosses the finish line, their bib number and their total duration in seconds is added to runners .

Now, the dutiful programmer in charge of handling the outcome data sees this list, knows that the top 5 fastest participants are the winners that get prizes, and the remaining runners are going to be sorted by fastest time.

There are no requirements for multiple types of sorting by various attributes. The list is a reasonable size. There is no mention of storing the list somewhere. Just sort by duration and grab the five participants with the lowest duration:

The programmer chooses to use a lambda in the key argument to get the duration attribute from each runner and sort runners in place using .sort() . After runners is sorted, the first 5 elements are stored in top_five_runners .

Mission accomplished! The race director comes over and informs the programmer that since the current release of Python is 3.7, they have decided that every thirty-seventh person that crossed the finish line is going to get a free gym bag.

At this point, the programmer starts to sweat because the list of runners has been irreversibly changed. There is no way to recover the original list of runners in the order they finished and find every thirty-seventh person.

If you’re working with important data, and there is even a remote possibility that the original data will need to be recovered, then .sort() is not the best option. If the data is a copy, of if it is unimportant working data, of if no one will mind losing it because it can be retrieved, then .sort() can be a fine option.

Alternatively, the runners could have been sorted using sorted() and using the same lambda :

In this scenario with sorted() , the original list of runners is still intact and has not been overwritten. The impromptu requirement of finding every thirty-seventh person to cross the finish line can be accomplished by interacting with the original values:

every_thirtyseventh_runners is created by using a stride in the list slice syntax on runners , which still contains the original order in which the runners crossed the finish line.

How to Sort in Python: Conclusion

.sort() and sorted() can provide exactly the sort order you need if you use them properly with both the reverse and key optional keyword arguments.

Both have very different characteristics when it comes to output and in-place modifications, so make sure you think through any application functionality or program that will be using .sort() as it can irrevocably overwrite data.

For the avid Pythonistas looking for a challenge with sorting, try using more complex data types in sorting: nested iterables. Also, feel free to dive into the open source Python code implementations for the built-ins and read about the sort algorithm used in Python called Timsort. And if you’re looking to sort dictionaries, then check out Sorting a Python Dictionary: Values, Keys, and More.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Sorting Data With Python

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About David Fundakowski

David is a Python developer with a background in database administration and development. He currently owns equipment to brew coffee 6 different ways.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Alex Ronquillo

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *