Sort List of Floats in Python (2 Examples)

In this tutorial youâ€™ll learn how to sort a list of floats in Python programming.

The table of content is structured as follows:

Sound good? Letâ€™s dive into it!

Exemplifying Data

Letâ€™s first construct some example data to illustrate how to sort a list of float numbers in Python.

`float_list = [1.5, 3.3, -0.87, 15.99, -3.0, 0]    # generating an example float list`

As seen float_list contains six float numbers as you can understand from the decimal points.

Example 1: Sorting with sort() Method

This example demonstrates how to use the sort() method for sorting a list of floats in ascending and descending order.

```float_list.sort()                                 # sorting the list ascending
print(float_list)                                 # printing the sorted list
# [-3.0, -0.87, 0, 1.5, 3.3, 15.99]```

When the reverse parameters are set to â€˜Trueâ€™, then the list will be sorted in a descending way.

```float_list.sort(reverse=True)                     # sorting the list descending
print(float_list)                                 # printing the sorted list
# [15.99, 3.3, 1.5, 0, -0.87, -3.0]```

You can see how the first element (-0.3) and last element (15.99) in float_list in ascending order are now placed in the last and first positions in float_list in descending order.

Example 2: Sorting using sorted() Function

In this example, the sorting will be done with the sorted() function.

```print(sorted(float_list))                         # sorting the list and printing
# [-3.0, -0.87, 0, 1.5, 3.3, 15.99]```

The difference between the sort() method and the sorted() function is that sort() method doesnâ€™t generate a new list. The sort() method transforms the list into the sorted version, however, the sorted() function returns a new list with the same elements but sorted. This means that the sorted() function doesnâ€™t alter the original list.

See how float_list still takes the same initial values by printing it.

```print(float_list)                                 # printing float_list
# [1.5, 3.3, -0.87, 15.99, -3.0, 0]```

Once again if the reverse parameter is set to True then the sorting will be in a descending way.

```print(sorted(float_list, reverse=True))           # sorting in reverse and printing
# [15.99, 3.3, 1.5, 0, -0.87, -3.0]```

You can compare and see that the same results were obtained with Example 1.

Video & Further Resources

Do you need further information on the topics of this page? Then I recommend having a look at the following video on my YouTube channel. Iâ€™m demonstrating the contents of this tutorial in the video.

This page was created in collaboration with Ã–mer Ekiz. Have a look at Ã–merâ€™s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.

Subscribe to the Statistics Globe Newsletter