Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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.

  • + Share This
  • 🔖 Save To Your Account