Thursday, August 19, 2021

Python Sort And Sorted

Python Sort And Sorted

In this notebook, we will learn about how to use Python sort and sorted methods to sort different types of data structures.

Let us start with simple example.

Let us initialize a Python list of numbers.

In [1]:
# initializing a list
digits = [4, 3, 5, 1, 2, 0, 6]

To sort, Python has sort() method. By default Python Sort the numbers in ascending order that is from low to high.

In [2]:
# sorting the digits
digits.sort()
# printing the digits
print(digits)
[0, 1, 2, 3, 4, 5, 6]

To sort the number in increasing order, specify the option "reverse"=True as shown below.

In [3]:
# initializing a list
digits = [4, 3, 7, 5, 1, 2, 0, 6]
# sorting the digits in descending order
digits.sort(reverse=True)
# printing the digits
print(digits)
[7, 6, 5, 4, 3, 2, 1, 0]
Sort the Python list based on absolute value

Let us say, we have list of negative and positive numbers in a list and

(continued...)

from Planet SciPy
read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...