Python Program to sort the elements of a given list in Ascending and Descending Order

Here, we will figure out how to sort the components of a list in Ascending and Descending request in Python?

Given a list of the components and we need to sort the list in Ascending and the Descending request in Python.

Python list.sort() Method

sort() is an inbuilt strategy in Python, it is utilized to sort the components/objects of the list in Ascending and Descending Order.

Arranging components in Ascending Order (list.sort())

Syntax:

 list.sort()

Program to sort list components in Ascending Order:

# List of integers
num = [10, 30, 40, 20, 50]

# sorting and printing 
num.sort()
print (num)

# List of float numbers
fnum = [10.23, 10.12, 20.45, 11.00, 0.1]

# sorting and printing
fnum.sort()
print (fnum)

# List of strings 
str = ["Banana", "Cat", "Apple", "Dog", "Fish"]

# sorting and  printing
str.sort()
print (str)

Output:

    [10, 20, 30, 40, 50]
    [0.1, 10.12, 10.23, 11.0, 20.45]
    ['Apple', 'Banana', 'Cat', 'Dog', 'Fish']

Arranging in Descending Order (list.sort(reverse=True))

To sort a list in the diving request, we pass reverse=True as contention with sort() strategy.

Syntax:

 list.sort(reverse=True)

Program to sort list components in Descending Order:

# List of integers
num = [10, 30, 40, 20, 50]

# sorting and printing 
num.sort(reverse=True)
print (num)

# List of float numbers
fnum = [10.23, 10.12, 20.45, 11.00, 0.1]

# sorting and printing
fnum.sort(reverse=True)
print (fnum)

# List of strings 
str = ["Banana", "Cat", "Apple", "Dog", "Fish"]

# sorting and  printing
str.sort(reverse=True)
print (str)

Output:

    [50, 40, 30, 20, 10]
    [20.45, 11.0, 10.23, 10.12, 0.1]
    ['Fish', 'Dog', 'Cat', 'Banana', 'Apple']

Leave a Comment

error: Alert: Content is protected!!