Logo
  • Ubuntu
  • CentOS
  • Debian
  • Fedora
  • RedHat

Python List Sort - DesignLinux

designlinux 0 Comments

Sorting data is one of the most common tasks when working with Python. For example, you may want to sort a list of team members by name, or a list of projects in order of priority.

This article describes how to sort lists in Python.

Python sort() and sorted() #

In Python, you can sort a list using the built-in list.sort() method or the built-in sorted() function.

The sorted() function creates a new sorted list, while the list.sort() method sorts the list in place. If you want to keep, the unsorted list use the sorted() function. Another difference is that the sorted() function works on any iterable object.

The syntax of sort() and sorted() is as follows:

list.sort(key=function, reverse=Boolean)
sorted(iterable, key=function, reverse=Boolean)

The optional keyword arguments key and reverse have the following meaning:

  • key – Function that takes one argument and transforms it before the comparison. The function must return one value that is used for the sort comparison.
  • reverse – The value of reverse can be either True or False. The default value is True. When this argument is set to false, the list is sorted in reverse order.

Elements of the list are compared using the “less than” (<) operator and sorted in ascending order. The < operator doesn’t support comparing a string to an integer, so if you have a list containing strings and integers, the sort operation will fail.

The following example shows how to sort a list of strings in alphabetical order:

directions = ["north", "east", "south", "west"] 

directions.sort()

print('Sorted list:', directions)
Sorted list: ['east', 'north', 'south', 'west']

If you want to keep the original list unchanged use the sorted() function:

directions = ["north", "east", "south", "west"] 

sorted_directions = sorted(directions)

print('Sorted list:', sorted_directions)
Sorted list: ['east', 'north', 'south', 'west']

To sort the list in reverse (descending) order set the reverse argument to True:

directions = ["north", "east", "south", "west"] 

directions.sort(reverse=True)

print('Sorted list:', directions)
Sorted list: ['west', 'south', 'north', 'east']

Sorting with Function #

The key argument accepts a function and allows you to perform more complex sorting operations.

The most simple example would be to sort the elements according to their length:

directions = ["Arya", "Daenerys", "Jon", "Brienne"] 

directions.sort(key=len)

print('Sorted list:', directions)

We’re using the len() function to return the number of characters in the string, which is used as a comparator:

Sorted list: ['Jon', 'Arya', 'Brienne', 'Daenerys']

You can also create a custom function and use it as a key argument for comparison. Here is an example showing how to sort a list of integers according to the sum of their digits:


def sum_digits(num): 
    digits = [int(x) for x in str(num)] 
    return sum(digits) 
      
numbers = [23, 77, 19, 310, 219] 

numbers.sort(reverse=True, key=sum_digits)

print('Sorted list:', numbers)
Sorted list: [77, 219, 19, 23, 310]

Another example would be to use the key argument to sort a complex list, such as list of tuples:

numbers = [(3, 14), (1, 61), (2, 71)]

numbers.sort(key=lambda k: k[0])

print('Sorted list:', numbers)

We’re using an anonymous (lambda) function that returns the first element of the tuple. The list is sorted by the value returned from the function:

Sorted list: [(1, 61), (2, 71), (3, 14)]

The same approach can be used to sort a list of dictionaries:

elements = [
    {'name': 'Germanium', 'number': 25, 'symbol': 'ge'},
    {'name': 'Silver', 'number': 47, 'symbol': 'ag'},
    {'name': 'Iron', 'number': 26, 'symbol': 'fe'},
]

elements.sort(key=lambda k: k['name'])

print('Sorted list:', elements)

The lambda function returns the value of the name key, which is used for comparison:

Sorted list: [
    {'name': 'Germanium', 'number': 25, 'symbol': 'ge'}, 
    {'name': 'Iron', 'number': 26, 'symbol': 'fe'}, 
    {'name': 'Silver', 'number': 47, 'symbol': 'ag'}
]

A better and faster way to sort a complex function is to use the Operator module functions. Here is an example:

from operator import itemgetter

elements = [
    {'name': 'Germanium', 'number': 25, 'symbol': 'ge'},
    {'name': 'Silver', 'number': 47, 'symbol': 'ag'},
    {'name': 'Iron', 'number': 26, 'symbol': 'fe'},
]

elements.sort(key=itemgetter('symbol')) 

print('Sorted list:', elements)

The itemgetter function fetches the value of the key symbol:

Sorted list: [
    {'name': 'Silver', 'number': 47, 'symbol': 'ag'},
    {'name': 'Iron', 'number': 26, 'symbol': 'fe'},
    {'name': 'Germanium', 'number': 25, 'symbol': 'ge'}
]

Conclusion #

We have shown you how to sort lists in Python using the sort() method and sorted() function.

If you have any questions or feedback, feel free to leave a comment.

python

Related

Tags: python

Zorin OS 15 – An Ultimate Linux Desktop Designed for Windows and macOS Users

Prev Post

How to Install Xrdp Server (Remote Desktop) on CentOS 8

Next Post
Archives
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • July 2022
  • June 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021
  • May 2021
  • April 2021
  • March 2021
  • February 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
Categories
  • AlmaLinux
  • Android
  • Ansible
  • Apache
  • Arch Linux
  • AWS
  • Backups
  • Bash Shell
  • Bodhi Linux
  • CentOS
  • CentOS Stream
  • Chef
  • Cloud Software
  • CMS
  • Commandline Tools
  • Control Panels
  • CouchDB
  • Data Recovery Tools
  • Databases
  • Debian
  • Deepin Linux
  • Desktops
  • Development Tools
  • Docker
  • Download Managers
  • Drupal
  • Editors
  • Elementary OS
  • Encryption Tools
  • Fedora
  • Firewalls
  • FreeBSD
  • FTP
  • GIMP
  • Git
  • Hadoop
  • HAProxy
  • Java
  • Jenkins
  • Joomla
  • Kali Linux
  • KDE
  • Kubernetes
  • KVM
  • Laravel
  • Let's Encrypt
  • LFCA
  • Linux Certifications
  • Linux Commands
  • Linux Desktop
  • Linux Distros
  • Linux IDE
  • Linux Mint
  • Linux Talks
  • Lubuntu
  • LXC
  • Mail Server
  • Manjaro
  • MariaDB
  • MongoDB
  • Monitoring Tools
  • MySQL
  • Network
  • Networking Commands
  • NFS
  • Nginx
  • Nodejs
  • NTP
  • Open Source
  • OpenSUSE
  • Oracle Linux
  • Package Managers
  • Pentoo
  • PHP
  • Podman
  • Postfix Mail Server
  • PostgreSQL
  • Python
  • Questions
  • RedHat
  • Redis Server
  • Rocky Linux
  • Security
  • Shell Scripting
  • SQLite
  • SSH
  • Storage
  • Suse
  • Terminals
  • Text Editors
  • Top Tools
  • Torrent Clients
  • Tutorial
  • Ubuntu
  • Udemy Courses
  • Uncategorized
  • VirtualBox
  • Virtualization
  • VMware
  • VPN
  • VSCode Editor
  • Web Browsers
  • Web Design
  • Web Hosting
  • Web Servers
  • Webmin
  • Windows
  • Windows Subsystem
  • WordPress
  • Zabbix
  • Zentyal
  • Zorin OS
Visits
  • 3
  • 603
  • 1,055,375

DesignLinux.com © All rights reserved

Go to mobile version