Skip to main content

Sorting in Python Tutorial

Discover what the sort method is and how to do it.
Jul 2020  · 1 min read

The sort() method is a built-in Python method that, by default, sorts the list in ascending order. However, you can modify the order from ascending to descending by specifying the sorting criteria.

sort() Method

Let's say you want to sort the element in prices in ascending order. You would type prices followed by a . (period) followed by the method name, i.e., sort including the parentheses.

prices = [238.11, 237.81, 238.91]
prices.sort()
print(prices)
[237.81, 238.11, 238.91]

Printing Sorted Lists

Again, using a similar example as above, we will use the .sort() method to sort and print the prices in the list named prices.

prices = [159.54, 37.13, 71.17]
prices.sort()
print(prices)
[37.13, 71.17, 159.54]

Try it for yourself.

To learn more about sorting in Python, please see this video from our course Introduction to Python for Finance.

This content was taken from DataCamp’s Introduction to Python for Finance course by Adina Howe.

Other Python Courses

Introduction to Python

Beginner
4 hr
4.7M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Inside Our Favorite DataFramed Episodes of 2022

An inside look at our favorite episodes of the DataFramed podcast of 2022
Adel Nehme's photo

Adel Nehme

2 min

[Infographic] Data Science Project Checklist

Use this checklist when planning your next data science project.
Adel Nehme's photo

Adel Nehme

ChatGPT Cheat Sheet for Data Science

In this cheat sheet, gain access to 60+ ChatGPT prompts for data science tasks.
Travis Tang's photo

Travis Tang

10 min

An Introduction to Python Subprocess: Basics and Examples

Explore our step-by-step guide to running external commands using Python's subprocess module, complete with examples.
Moez Ali's photo

Moez Ali

15 min

Setting Up VSCode For Python: A Complete Guide

Experience a simple, fun, and productive way of Python development by learning about VSCode and its extensionsn and features.
Abid Ali Awan's photo

Abid Ali Awan

16 min

GeoPandas Tutorial: An Introduction to Geospatial Analysis

Get started with GeoPandas, one of the most popular Python libraries for geospatial analysis.
Javier Canales Luna's photo

Javier Canales Luna

15 min

See MoreSee More