Python Program to find N largest numbers in a list

This tutorial will show you how to find the ‘n’ largest numbers in a list using Python.

We are taking inputs from the user. But if you wish to do this without taking input from the user, you can also do this. Just remove the user input part and instead of that just create a list variable.

# We take the list of numbers and the number of largest numbers to be found from the user

print("Enter Numbers in The List Seperated By a Space : ")
numbers = list(map(int,input().split()))

n = int(input("Enter the number of largest numbers you want to find in the list : "))

# We sort the list of numbers in reverse so that we get the largest numbers in the beginning of the list

numbers.sort(reverse=True)

counter=0
i=0

# The largest[] list is used to store the numbers so that we do not repeat the same number

largest = []

print("Largest "+str(n)+" numbers are :- ")

# We check if the number is present in the largest[] list. This is done to prevent repeated printing of
# the same number in case there is more than one instance of the largest numbers.

while(counter < n):
    if(numbers[i] not in largest):
        largest.append(numbers[counter])
        print(numbers[i])
        counter += 1
        i += 1
    else:
        i += 1

First, we take the list of numbers and the number of largest numbers that you want to get as output. We take this as input from the user.

Next, we sort the list of numbers in reverse order, This is so that we have easy access to the largest numbers at the beginning of our list.

We then create another list, ‘largest‘. This is done to store the largest numbers so that we know if any number is being repeated.

We check the ‘largest‘ list to check if the number is present. If no, then we print the number. This is repeated the number of times we want to print the largest numbers in the list.

OUTPUT

Enter Numbers in The List Seperated By a Space : 

5 5 3 2 1

Enter the number of largest numbers you want to find in the list : 3
Largest 3 numbers are :- 
5
3
2

CONCLUSION

Also check:

Array Sorting: How to sort an array of integers in Python3

Find the Second Largest value in a dictionary in Python

Leave a Reply

Your email address will not be published. Required fields are marked *