How to Sort Decimal Numbers in Python?

Estimated read time 1 min read

To sort decimal numbers in Python, you can use the built-in sort() or sorted() functions. By default, these functions sort numbers in ascending order. Here’s an example implementation:

# Define a list of decimal numbers
my_list = [3.14159, 1.61803, 2.71828, 0.69315, 1.41421]

# Sort the list in ascending order
my_list.sort()
print(my_list)  # Output: [0.69315, 1.41421, 1.61803, 2.71828, 3.14159]

sorted_list = sorted(my_list)
print(sorted_list)  # Output: [0.69315, 1.41421, 1.61803, 2.71828, 3.14159]

In this example, we define a list my_list of decimal numbers. We use the sort() function to sort the list in ascending order, and then print the sorted list. We also use the sorted() function to create a new sorted list and print it.

If you want to sort decimal numbers in descending order, you can pass the reverse=True argument to the sort() or sorted() function, like this:

# Sort the list in descending order
my_list.sort(reverse=True)
print(my_list)  # Output: [3.14159, 2.71828, 1.61803, 1.41421, 0.69315]

sorted_list = sorted(my_list, reverse=True)
print(sorted_list)  # Output: [3.14159, 2.71828, 1.61803, 1.41421, 0.69315]

In this example, we sort the list in descending order by passing reverse=True to the sort() and sorted() functions.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply