- Python: How to Sort a List (Strings / Numbers)
- Using sort() Function
- Sort List containing numbers (Integers and decimals)
- Sort List containing strings
- Sort list in reverse order using sort()
- Using sorted() Function
- Sort Numbers using sorted()
- Sort List with a key argument
- Useful Tip:
- Sort list containing both uppercase and lowercase strings
- Возможности и примеры функции sorted в Python
- Параметр key
- 1. Встроенная функция
- 2. Пользовательские функции
- 3. Лямбда-функция
Python: How to Sort a List (Strings / Numbers)
Python sorting functionality offers robust features to do basic sorting or customize ordering at a granular level.
In this Article, 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.
Using sort() Function
In Python, List has a native function to sort its items — sort() function. It can be used in different use-cases to sort the list. It is a very powerful function and can do custom sorting too by providing lambda function.
- The sort() function modifies the list in-place, therefore the list itself is modified and the function has no return value.
- It is a method of the *list *class and therefore can only be used with lists.
- By default, it sorts in ascending order
Sort List containing numbers (Integers and decimals)
Let’s review an example of sorting a list containing numbers. Sorting integers is quite simple as it compares using comparison operator and sorts accordingly.
Numbers = [1,32,8.4,5] Numbers.sort() print(Numbers) #[1,5,8.4,32]
Make sure all items are numbers since number and string cannot be compared via comparison operator »
Sort List containing strings
The sort() function can also be used to sort strings and it is quite robust as it not only compares first character, but subsequent characters if previous ones are same.
Let’s review one simple example:
Flowers = ["rose", "lotus", "lily", "sunflower"] Flowers.sort() print(Flowers) #['lily', 'lotus', 'rose', 'sunflower']
What if you want to compare only specific index in strings? That complex huh?
Let’s try to sort 3 phrases by 2nd character in third word of each phrase!
phrases = [ 'Barking Up The Wrong Tree' ,'Give a Man a Fish', 'A Fool and His Money are Soon Parted' ] phrases.sort(key=lambda x: x.split()[2][1]) phrases # ['Give a Man a Fish', 'Barking Up The Wrong Tree', 'A Fool and His Money are Soon Parted']
Here, we are using key parameter of sort function and providing a lambda function to extract 2nd character of 3rd word in each phrase and use it to sort the list. Pretty clever!
When sorting strings, you also need to pay attention to case since when sorting, sort() method sorts character using ASCII character, therefore Uppercase characters comes before lowercase in sorting.
Flowers = ["rose", "lotus", "lily", "Sunflower"] Flowers.sort() print(Flowers) #['Sunflower', 'lily', 'lotus', 'rose']
Sort list in reverse order using sort()
As sort() orders the list in ascending order by default, if you want to sort the list in descending order, you need to provide the order state as parameter.
Let’s see how we can sort the list in descending order:
Numbers = [1,32,8.4,5] Numbers.sort(reverse=True) print(Numbers) #[32, 8.4, 5, 1]
Using sorted() Function
Python also provides built-in function sorted() to sort all types of iterable data types like — lists, tuples, sets etc.
The sorted() and sort() are kind of similar with few differences. Therefore, either of them can be used to sort the list. We already talked about sort() function, so let’s talk about sorted().
- The sorted() method does not sort the list in-place. Therefore, it does not modify the list itself rather it returns new sorted list.
- It is a built-in method in python thus can be used on any kind of iterable variable including lists, tuples and sets
- By default, it sorts in ascending order
Sort Numbers using sorted()
Just like sort() function, we can sort numbers list using sorted() as well.
Numbers = [1,32,8.4,5] sortednumbers = sorted(Numbers) print(sortednumbers) #[1,5,8.4,32]
Similarly, you can sort list of strings as well using sorted() function.
Sort List with a key argument
Just like with sort() method, you can use key argument to customize sort logic when sorting a list.
Let’s try sorting the list of strings by length of the strings from smallest to biggest string:
Flowers = ["rose", "lotus", "lily", "sunflower"] sortedlist = sorted(Flowers, key=len) print(Flowers) # ['rose', 'lily', 'lotus', 'sunflower']
Two things to note in above example:
- We are passing len function to key parameter, therefore sorting function gets length of each string using len function and compares length of each string.
- The strings ‘rose‘ comes before ‘lily‘. Why? Since, we are sorting only by length, sorting function won’t change the order if length of strings are same. Therefore, ‘rose‘ and ‘lily‘ would remain as it is. In normal sorting, ‘lily‘ would come before ‘rose‘ in ascending order.
Useful Tip:
As we talked above, sorting list contained strings with both uppercase and lowercase is problematic. How to fix that?
Sort list containing both uppercase and lowercase strings
Remember, both sort() and sorted() function allows us to customize sorting functionality using key parameter.
Thus, we will use key argument, and will lowercase all strings before sorting them using str.lower function.
Not to worry about data mutation as key argument won’t actually modify our strings.
stringlist = ["rose", "lotus", "lily", "Sunflower"] sortedlist = sorted(stringlist) print(sortedlist) # ['Sunflower', 'lily', 'lotus', 'rose'] ==> OOPS # Let's fix it stringlist = ["rose", "lotus", "lily", "Sunflower"] sortedlist = sorted(stringlist, key=str.lower) print(sortedlist) # ['lily', 'lotus', 'rose', 'Sunflower']
Возможности и примеры функции sorted в Python
Функция sorted() возвращает новый отсортированный список итерируемого объекта (списка, словаря, кортежа). По умолчанию она сортирует его по возрастанию.
Сортировка строк осуществляется по ASCII-значениям.
- Возвращаемое значение — List (список).
- Синтаксис: sorted(iterable,key=None,reverse=False) .
- iterable : строка, список, кортеж, множество, словарь
- key (необязательный параметр): если указать ключ, то сортировка будет выполнена по функции этого ключа.
- reverse (необязательный параметр): по умолчанию сортировка выполняется по возрастанию. Если указать reverse=True , то можно отсортировать по убыванию.
# Сортировка строки
s2="hello"
print(sorted(s2)) # Вывод:['e', 'h', 'l', 'l', 'o']
print(sorted(s2, reverse=True)) # Вывод:['o', 'l', 'l', 'h', 'e']
# Сортировка списка
l1=[1, 4, 5, 2, 456, 12]
print(sorted(l1)) # Вывод:[1, 2, 4, 5, 12, 456]
print(sorted(l1, reverse=True)) # Вывод:[456, 12, 5, 4, 2, 1]
# Сортировка кортежа
t1=(15, 3, 5, 7, 9, 11, 42)
print(sorted(t1)) # Вывод:[3, 5, 7, 9, 11, 15, 42]
print(sorted(t1, reverse=True)) # Вывод:[42, 15, 11, 9, 7, 5, 3]
# Сортировка списка кортежей
t2=[(1, 2), (11, 12), (0, 2), (3, 2)]
print(sorted(t2)) # Вывод:[(0, 2), (1, 2), (3, 2), (11, 12)]
print(sorted(t2, reverse=True)) # Вывод:[(11, 12), (3, 2), (1, 2), (0, 2)]
# Сортировка множества
s1=
print(sorted(s1)) # Вывод:[1, 2, 3, 4, 6, 8, 11, 32]
print(sorted(s1, reverse=True)) # Вывод:[32, 11, 8, 6, 4, 3, 2, 1]
# Сортировка словаря
d1=
# Вернется список отсортированных ключей
print(sorted(d1)) # Вывод:[1, 2, 3]
# Вернется список отсортированных значений
print(sorted(d1.values())) # Вывод:['blue', 'green', 'red']
# Вернется список кортежей (ключ, значение), отсортированный по ключам.
print(sorted(d1.items())) # Вывод:[(1, 'green'), (2, 'red'), (3, 'blue')]
# Сортировка словаря в обратном порядке
print(sorted(d1, reverse=True)) # Вывод:[3, 2, 1]
print(sorted(d1.values(), reverse=True)) # Вывод:['red', 'green', 'blue']
print(sorted(d1.items(), reverse=True)) # Вывод:[(3, 'blue'), (2, 'red'), (1, 'green')]Параметр key
Итерируемый объект можно также отсортировать по функции, указанной в параметре key . Это может быть:
- Встроенная функция,
- Определенная пользователем функция,
- Лямбда-функция,
- itemgetter,
- attrgetter.
1. Встроенная функция
len() — посчитает длину объекта. Если указать len в виде параметра key, то сортировка будет выполнена по длине.
# Сортировка словаря на основе функции len
l1 =
# Возвращает список ключей, отсортированных по функции len
print(sorted(l1, key=len))
# Вывод: ['red', 'apple', 'carrot']
# Возвращает список значений, отсортированных на основе функции len
print(sorted(l1.values(), key=len))
# Вывод: ['fruit', 'color', 'vegetable']
# Сортировка списка на основе функции len
l1 = ['blue', 'green', 'red', 'orange']
print(sorted(l1, key=len))
# Вывод: ['red', 'blue', 'green', 'orange']abs() вернет абсолютно значение числа. Если задать abs для key , то сортировка будет основана на абсолютном значении.
# Сортировка списка по абсолютному значению
l1 = [1, -4, 5, -7, 9, 2]
print(sorted(l1, key=abs))
# Вывод: [1, 2, -4, 5, -7, 9]str.lower() — конвертирует все символы в верхнем регистре в нижний регистр. В таком случае список будет отсортирован так, будто бы все символы в нижнем регистре.
s1 = "Hello How are you"
# Разбивает строку и сортирует по словам
print(sorted(s1.split()))
# Вывод: ['Hello', 'How', 'are', 'you']
# Разбивает строку и сортирует после применения str.lower ко всем элементам
print(sorted(s1.split(), key=str.lower))
# Вывод: ['are', 'Hello', 'How', 'you']
d1 =
# Возвращает список ключей, отсортированный по значениям
print(sorted(d1))
# Вывод: ['Banana', 'Pears', 'apple']
# Возвращает список ключей, отсортированный после применения str.lower ко всем элементам
print(sorted(d1, key=str.lower))
# Вывод: ['apple', 'Banana', 'Pears']2. Пользовательские функции
Также можно указывать свои функции.
Пример №1: по умолчанию сортировка кортежа происходит по первому элементу в нем. Добавим функцию, которая будет возвращать второй элемент кортежа. Теперь и сортировка будет опираться на соответствующий элемент.
# напишем функцию для получения второго элемента
def sort_key(e):
return e[1]
l1 = [(1, 2, 3), (2, 1, 3), (11, 4, 2), (9, 1, 3)]
# По умолчанию сортировка выполняется по первому элементу
print(sorted(l1))
# Вывод: [(1, 2, 3), (2, 1, 3), (9, 1, 3), (11, 4, 2)]
# Сортировка по второму элементу с помощью функции sort_key
print(sorted(l1, key=sort_key))
# Вывод: [(2, 1, 3), (9, 1, 3), (1, 2, 3), (11, 4, 2)]Пример №2: можно сортировать объекты класса с помощью функций. Вот как это происходит:
- У класса Studen есть три атрибута: name , rollno , grade .
- Создаются три объекта этого класса: s1 , s2 , s3 .
- Создается список s4 , который содержит все три объекта.
- Дальше происходит сортировка по этому списку.
- Определенная функция ( sort_key ) возвращает атрибут rollno .
- В функции sorted эта функция задана для параметра key .
- Теперь sorted() возвращает список объектов Student , которые отсортированы по значению rollno .
class Student:
def __init__(self, name, rollno, grade):
self.name = name
self.rollno = rollno
self.grade = grade
def __repr__(self):
return f"--"
# Создание объектов
s1 = Student("Paul", 15, "second")
s2 = Student("Alex", 12, "fifth")
s3 = Student("Eva", 21, "first")
s4 = [s1, s2, s3]
# Сортировка списка объектов
# Создание функции, которая вернет rollno объекта
def sort_key(s):
return s.rollno
# сортировка списка объектов без ключевого параметра, вызывает TypeError
print(sorted(s4))
# Вывод: TypeError: '>' not supported between instances of 'Student' and 'Student'
# Сортировка списка объектов по атрибуту: rollno
s5 = sorted(s4, key=sort_key)
print(s5)
# Вывод: [Alex-12-fifth, Paul-15-second, Eva-21-first]3. Лямбда-функция
Также в качестве ключа можно задать лямбда-функцию. Сортировка будет выполняться по ней.
Пример №1: сортировка списка объектов класса на основе лямбда-функции, переданной для параметра key .