Find N Largest Elements in Python

Find the N largest elements in a list.

BeginnerList ProgramsExample 13 of 25
find-n-largest-elements.py
1# Program to find N largest elements in a list
2
3numbers = list(map(float, input("Enter numbers separated by space: ").split()))
4N = int(input("Enter N: "))
5
6if N <= 0:
7 print("N must be positive.")
8else:
9 largest = sorted(numbers, reverse=True)[:N]
10 print(f"{N} largest elements:", largest)

Output

Enter numbers separated by space: 1 3 5 2 4
Enter N: 3
3 largest elements: [5.0, 4.0, 3.0]

What's going on

We sort in descending order and slice the first N elements.

After this program

If the idea is still fuzzy, read Day 5: Lists and List Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 list programs, or see every topic on Python exercises.