Direkt zum Inhalt

Sorting in Python Tutorial

Discover what the sort method is and how to do it.
22. Juli 2020  · 1 Min. Lesezeit

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.

Themen

Other Python Courses

Kurs

Einführung in Python

4 Std.
6.5M
Lerne in nur vier Stunden die Grundlagen der Datenanalyse mit Python und entdecke beliebte Python-Pakete.
Siehe DetailsRight Arrow
Kurs starten
Mehr anzeigenRight Arrow
Verwandt

Lernprogramm

Pandas Sort Values: A Complete How-To

Use sort_values() to reorder rows by column values. Apply sort_index() to rearrange rows by the DataFrame’s index. Combine both methods to explore your data from different angles.
DataCamp Team's photo

DataCamp Team

Lernprogramm

Python Dictionary Tutorial

In this Python tutorial, you'll learn how to create a dictionary, load data in it, filter, get and sort the values, and perform other dictionary operations.
DataCamp Team's photo

DataCamp Team

Lernprogramm

Python Tutorial for Beginners

Get a step-by-step guide on how to install Python and use it for basic data science functions.
Matthew Przybyla's photo

Matthew Przybyla

Lernprogramm

Sorting in R using order() Tutorial

In this tutorial, you'll learn about sorting using order(). We will cover how to sort vectors using different parameters, sorting dataframes, and more.

Olivia Smith

Lernprogramm

Tuples in Python Tutorial

Learn to use and unpack Tuples in Python.
DataCamp Team's photo

DataCamp Team

Lernprogramm

Python Functions: How to Call & Write Functions

Discover how to write reusable and efficient Python functions. Master parameters, return statements, and advanced topics like lambda functions. Organize your code better with main() and other best practices.
Karlijn Willems's photo

Karlijn Willems

Mehr anzeigenMehr anzeigen