- 5.1 Introduction
- 5.2 Lists
- 5.3 Tuples
- 5.4 Unpacking Sequences
- 5.5 Sequence Slicing
- 5.6 del Statement
- 5.7 Passing Lists to Functions
- 5.8 Sorting Lists
- 5.9 Searching Sequences
- 5.10 Other List Methods
- 5.11 Simulating Stacks with Lists
- 5.12 List Comprehensions
- 5.13 Generator Expressions
- 5.14 Filter, Map and Reduce
- 5.15 Other Sequence Processing Functions
- 5.16 Two-Dimensional Lists
- 5.17 Intro to Data Science: Simulation and Static Visualizations
- 5.18 Wrap-Up
5.8 Sorting Lists
Sorting enables you to arrange data either in ascending or descending order.
Sorting a List in Ascending Order
List method sort modifies a list to arrange its elements in ascending order:
In [1]: numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6] In [2]: numbers.sort() In [3]: numbers Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sorting a List in Descending Order
To sort a list in descending order, call list method sort with the optional keyword argument reverse- set to True (False is the default):
In [4]: numbers.sort(reverse=True) In [5]: numbers Out[5]: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Built-In Function sorted
Built-in function sorted returns a new list containing the sorted elements of its argument sequence—the original sequence is unmodified. The following code demonstrates function sorted for a list, a string and a tuple:
In [6]: numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6] In [7]: ascending_numbers = sorted(numbers) In [8]: ascending_numbers Out[8]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [9]: numbers Out[9]: [10, 3, 7, 1, 9, 4, 2, 8, 5, 6] In [10]: letters = 'fadgchjebi' In [11]: ascending_letters = sorted(letters) In [12]: ascending_letters Out[12]: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] In [13]: letters Out[13]: 'fadgchjebi' In [14]: colors = ('red', 'orange', 'yellow', 'green', 'blue') In [15]: ascending_colors = sorted(colors) In [16]: ascending_colors Out[16]: ['blue', 'green', 'orange', 'red', 'yellow'] In [17]: colors Out[17]: ('red', 'orange', 'yellow', 'green', 'blue')
Use the optional keyword argument reverse with the value True to sort the elements in descending order.