Python program to find N largest elements from a list

ProgrammingPythonServer Side Programming

In this example, we will see how to find the N largest elements from a List. The list is the most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that the items in a list need not be of the same type

Let’s say the following is the input list −

[25, 18, 29, 87, 45, 67, 98, 5, 59]

The following is the output displaying the N largest element from the list. Here, N = 3 −

[98, 87, 67]

Python program to find N largest elements from a list with for loop

We will use a for loop here to find the N largest elements from a List −

Example

def LargestFunc(list1, N): new_list = [] for i in range(0, N): max1 = 0 for j in range(len(list1)): if list1[j] > max1: max1 = list1[j]; list1.remove(max1); new_list.append(max1) print("Largest numbers = ",new_list) # Driver code my_list = [12, 61, 41, 85, 40, 13, 77, 65, 100] N = 4 # Calling the function LargestFunc(my_list, N)

Output

Largest numbers = [100, 85, 77, 65]

Python program to find N largest elements from a list using the sort()

We will use a built-in function sort() to find the N largest elements from a List −

Example

# Create a List myList = [120, 50, 89, 170, 45, 250, 450, 340] print("List = ",myList) # The value of N n = 4 # First, sort the List myList.sort() # Now, get the largest N integers from the list print("Largest integers from the List = ",myList[-n:])

Output

List = [120, 50, 89, 170, 45, 250, 450, 340]
Largest integers from the List = [170, 250, 340, 450]
raja
Updated on 11-Aug-2022 12:41:41

Advertisements