Python Program to sort the elements of an array

Python Program to sort the elements of an array

Sort the Array in Python

Here, in this page we will discuss the program to sort elements of the given array in Python programming language. We will discuss the program to sort the given input array using inbuilt sort function.

Here, in this page we will sort the given input array but not only in ascending order, but also in descending order.

Example :

  • Input : arr[5] = [10, 40, 20, 30]
  • Output : In ascending order = 10 20 30 40
                   In descending order = 40 30 20 10

Method 1 (Sort in ascending order):

In this method we will sort the given input array using inbuilt sort function.

  • Declare an array.
  • Call sort() function i.e, arr.sort()

This will sort the given input array in ascending order. We will also discuss to sort the given input array in descending order as well.

Sort the array in python

Code to Sort the Array in Python

Run
# List of Integers
numbers = [10, 30, 40, 20]

# Sorting list of Integers
numbers.sort()

print(numbers)

Output

[10, 20, 30, 40]

Method 2 (Sort in descending order):

In this method we will sort the given input array using inbuilt sort function.

  • Declare an array.
  • Call sort() function i.e, arr.sort(reverse=True)

This will sort the given input array in descending order.

Code to Sort the Array in Python

Run
# List of Integers
numbers = [10, 30, 40, 20]

# Sorting list of Integers
numbers.sort(reverse=True)

print(numbers)

Output

[40, 30, 20, 10]
 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

3 comments on “Python Program to sort the elements of an array”


  • SUMAN

    #decending order
    a1 = list(map(int,input().split(“,”)))
    a1.sort(reverse = True);
    print(a1);


  • SUMAN

    **Asscending order
    a1 = list(map(int,input().split(“,”)))
    a1.sort();
    print(a1);


  • Anirudh

    n = int(input())
    arr = []
    for i in range(n):
    e = int(input())
    arr.append(e)
    print(arr)
    arr.sort()
    print(“A.O.”,arr)
    arr.sort(reverse=True)
    print(“D.O.”,arr)