Construction Powerhouse
Sorting in Python is a fundamental task that you can accomplish using sorted() and .sort(). The sorted() function returns a new sorted list from the elements of any iterable, without modifying the original iterable. On the other hand, the .sort() method modifies a list in place and doesn’t return a value. Both methods support customization through optional keyword arguments like key and reverse.
By the end of this tutorial, you’ll understand that:
- You can sort any iterable with the sorted() function.
- The sorted() function returns a new sorted list.
- The .sort() method sorts the list in place.
- You sort items in descending order by setting the reverse argument to True.
- The key argument accepts a function to customize the sort order.
In this tutorial, you’ll learn how to sort various types of data in different data structures, customize the order, and work with two different ways of sorting in Python. You’ll need a basic understanding of lists and tuples as well as sets. These are the data structures you’ll be using to perform some basic operations.
Ordering Values With sorted()
In Python, you can sort iterables with the sorted() built-in function. To get started, you’ll work with iterables that contain only one data type.
Sorting Numbers
You can use sorted() to sort a list in Python. In this example, a list of integers is defined, and then sorted() is called with the numbers variable as the argument:
cd Terraform
Sorting Strings
Just like lists, tuples, and sets, strings are also iterables. This means you can sort str types as well. The example below shows how sorted() iterates through each character in the value passed to it and orders them in the output:
sed -i "s|<placeholder_app>|$(terraform output -raw public_ip)|g" ../Ansible/inventory
Just like before, you can use sorted() to iterate through each element of the iterable you pass in. In a string, each element means each character, including spaces.
Exploring Limitations and Gotchas With Python Sorting
When sorting objects in Python, you may run into some unexpected behavior or even errors. In this section, you’ll explore some limitations and gotchas to look out for when using Python’s sorted() function.
Handling Lists With Non-Comparable Data Types
There are data types that can’t be compared to each other using sorted() because they’re too different. Python will return an error if you attempt to use sorted() on a list containing non-comparable data. In the example below, you have None and the integer zero (0) in the same list. Python doesn’t know how to sort these two types because of their incompatibility:
cat ../Ansible/inventory
Customizing sorted() With Keyword Arguments
When using Python’s sorted() function, you can optionally pass in values for the keywords reverse and key. This enables you to override the default behavior of sorted() and customize the order of the output.
Sorting Iterables in Reverse Order
As the name suggests, the keyword argument reverse let’s you reverse the order of an iterable. The reverse keyword accepts a Boolean value:
terraform output -raw private_key > ../Ansible/myKey.pem
Ordering Values With .sort()
So far, you’ve learned about Python’s sorted() function. However, you may have come across a method with a similar name—the .sort() method:
---
# This playbook will be executed on all hosts defined in the inventory.
- hosts: all
become_user: root # Run all tasks as the root user.
become: true # Enable privilege escalation (sudo) for all tasks.
tasks:
- name: Install pip3 and unzip
apt:
update_cache: yes # Update the package index before installing.
pkg:
- python3-pip # Install the Python3 package installer.
- unzip # Install the unzip utility.
register: result # Register the result of the task to a variable named 'result'.
until: result is not failed # Retry until the task succeeds.
retries: 5 # Retry up to 5 times.
delay: 5 # Wait 5 seconds between retries.
- name: Add Docker GPG apt Key
apt_key:
url: https://download.docker.com/linux/ubuntu/gpg # URL for Docker's official GPG key.
state: present # Ensure the GPG key is added.
- name: Add Docker Repository
apt_repository:
repo: deb https://download.docker.com/linux/ubuntu focal stable # Add the Docker repository for Ubuntu Focal (20.04).
state: present # Ensure the repository is present.
- name: Update apt and install docker-ce
apt:
name: docker-ce # Install the latest version of Docker Community Edition (CE).
state: latest # Ensure the latest version of Docker CE is installed.
update_cache: true # Update the package index before installing.
- name: Install Docker module for Python
pip:
name: docker # Install the Docker module for Python using pip.
- name: Pull the Jenkins Docker image
docker_image:
name: "samgabrail/jenkins-tf-vault-ansible:latest" # Specify the Jenkins Docker image to pull.
source: pull # Ensure the image is pulled from the repository.
state: present # Ensure the image is present.
force_source: yes # Force a fresh pull of the image, even if it already exists.
- name: Change file ownership, group and permissions
file:
path: /home/ubuntu/jenkins_data # Path to the Jenkins data directory on the host.
state: directory # Ensure this path is a directory.
recurse: yes # Apply the permissions recursively to all files and subdirectories.
owner: ubuntu # Set the owner of the directory to the 'ubuntu' user.
group: ubuntu # Set the group of the directory to 'ubuntu'.
- name: Create Jenkins container
docker_container:
name: "jenkins" # Name of the Docker container to be created.
image: "samgabrail/jenkins-tf-vault-ansible:latest" # Use the Jenkins Docker image pulled earlier.
state: started # Ensure the container is started and running.
ports:
- "8080:8080" # Map port 8080 on the host to port 8080 in the container (Jenkins UI).
- "50000:50000" # Map port 50000 on the host to port 50000 in the container (Jenkins agent).
volumes:
- /home/ubuntu/jenkins_data:/var/jenkins_home # Mount the Jenkins data directory on the host to the appropriate path in the container.
🐍 Python Tricks 💌
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.
— FREE Email Series —
Python Tricks
🔒 No spam. Unsubscribe any time.