Home ยป Sort a List in Ascending Order in Python

Sort a List in Ascending Order in Python

Java SE 11 Programmer I [1Z0-815] Practice Tests
1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]
Oracle Java Certification
Java SE 11 Programmer II [1Z0-816] Practice Tests
Spring Framework Basics Video Course

In this article we show how to sort a list in ascending order in python

Example

We use a for loop to add numbers to the Python list using the append method

We then use the sort method to sort the List items in ascending order.

# Sort a List in Ascending Order
myList = []

Number = int(input("Please enter the Number of List Elements: "))
for i in range(1, Number + 1):
    value = int(input("Please enter the Value of Element %d : " %i))
    myList.append(value)

myList.sort()

print("Sorted List in Ascending Order is : ", myList)

When you run this you will see something like this

>>> %Run listascend.py
Please enter the Number of List Elements: 6
Please enter the Value of Element 1 : 10
Please enter the Value of Element 2 : 50
Please enter the Value of Element 3 : 30
Please enter the Value of Element 4 : 20
Please enter the Value of Element 5 : 60
Please enter the Value of Element 6 : 40
Sorted List in Ascending Order is :  [10, 20, 30, 40, 50, 60]

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More