Program to find the nth largest numbers in the list using Python

Introduction

In this section of python programming, we will find the n largest numbers in the given list.

Program to find the nth largest numbers in the list

Program

list = [10, 15, 20, 70]
list1 = [1, 5, 7, 10]
n = int(input("Enter the nth number to find n largest number: "))
# Using sort()
list_copy = list
list.sort()
print("The {0} largest numbers in the given list {1} is {2}".format(n, list_copy, list[-n:]))
# Uisng traversal
list1_copy = set(list1)


def n_largest(list1, n):
    output_list = []
    for i in range(0, n):
        max_ele = 0
        for j in range(len(list1)):
            if list1[j] > max_ele:
                max_ele = list1[j];
        list1.remove(max_ele);
        output_list.append(max_ele)
    output_list.sort()
    return output_list
print("The {0} largest numbers in the given list {1} is {2}".format(n, list1_copy, n_largest(list1, n)))

 

Output

Program to find the nth largest numbers in the list Output

Explanation

In the above python program, we have used simple traversal method and sort() function to find the nth largest elements in the given list. Using sort(), all the elements in the list are sorted in ascending order and after that we printed all the n elements from right that is required using slicing property of list.

In traversal method, we have found the max element, stored in the variable output_list and then removed from the list. The traversal process continues until we have found all the n elements required by the user.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.