Home » Python programs

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

Here, we are going to learn how to sort the elements of a list in Ascending and Descending order in Python?
Submitted by IncludeHelp, on July 24, 2018

Given a list of the elements and we have to sort the list in Ascending and the Descending order in Python.

Python list.sort() Method

sort() is a inbuilt method in Python, it is used to sort the elements/objects of the list in Ascending and Descending Order.

Sorting elements in Ascending Order (list.sort())

Syntax:

 list.sort()

Program to sort list elements 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']

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

To sort a list in descending order, we pass reverse=True as an argument with sort() method.

Syntax:

 list.sort(reverse=True)

Program to sort list elements 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']





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.