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]
Let us say, we have list of negative and positive numbers in a list and
from Planet SciPy
read more
No comments:
Post a Comment